Saturday, February 17, 2018

Checked Exception vs Unchecked Exception



This notes are adapted from the followings links:
https://www.geeksforgeeks.org/checked-vs-unchecked-exceptions-in-java/
https://stackoverflow.com/questions/7049623/how-to-create-checked-unchecked-custom-exceptions-in-java
https://docs.oracle.com/javase/tutorial/essential/exceptions/catchOrDeclare.html
https://beginnersbook.com/2013/04/java-throws/
https://www.journaldev.com/592/java-try-with-resources

The term exception is shorthand for the phrase "exceptional event."

Definition: An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program's instructions.


When an error occurs within a method, the method creates an object and hands it off to the runtime system. The object, called an exception object, contains information about the error, including its type and the state of the program when the error occurred. Creating an exception object and handing it to the runtime system is called throwing an exception.
After a method throws an exception, the runtime system attempts to find something to handle it. The set of possible "somethings" to handle the exception is the ordered list of methods that had been called to get to the method where the error occurred. The list of methods is known as the call stack (see the next figure).
The call stack showing three method calls, where the first method called has the exception handler.
The call stack.
The runtime system searches the call stack for a method that contains a block of code that can handle the exception. This block of code is called an exception handler. The search begins with the method in which the error occurred and proceeds through the call stack in the reverse order in which the methods were called. When an appropriate handler is found, the runtime system passes the exception to the handler. An exception handler is considered appropriate if the type of the exception object thrown matches the type that can be handled by the handler.
The exception handler chosen is said to catch the exception. If the runtime system exhaustively searches all the methods on the call stack without finding an appropriate exception handler, as shown in the next figure, the runtime system (and, consequently, the program) terminates.
The call stack showing three method calls, where the first method called has the exception handler.
Searching the call stack for the exception handler.
Using exceptions to manage errors has some advantages over traditional error-management techniques. You can learn more in the Advantages of Exceptions section.


In Java exceptions 
1> under Error and RuntimeException classes are unchecked 
2> exceptions, everything else under throwable is checked.

                   +-----------+
                   | Throwable |
                   +-----------+
                    /         \
                   /           \
          +-------+          +-----------+
          | Error |          | Exception |
          +-------+          +-----------+
           /  |  \            / |        \
         \________/         \______/      \
                                       +------------------+
          unchecked         checked    | RuntimeException |
                                       +------------------+
                                         /   |    |      \
                                       \_________________/
        
                                            unchecked 


Checked exception: are the exceptions that are checked at compile time. If some code within a method throws a checked exception, then the method must either handle the exception or it must specify the exception using throws keyword.

Every exception in Java is a checked exception unless it extends RuntimeException

class CheckedException extends Exception {
}
Checked exception must be handled with try catch block or the methods must throw the exception explicitly.
eg: The following won't compile at all


We need to use try catch to surround the function which throws excepitons

or let the function forward the exceptions to the next one

UnChecked exception: the exceptions that are not checked at compiled time. 

The Exception extends RuntimeException


Every exception in Java is a checked exception unless it extends RuntimeException

class UnCheckedException extends RunTimeException {
}

Choose checked or unchecked exceptions?

If a client can reasonably be expected to recover from an exception, make it a checked exception

If a client cannot do anything to recover from the exception, make it an unchecked exception.

Note: the followings won't throw exception during Compiling stage, it only throws exception in runtime, because ArithmeticException is an unchecked exception.




Note:

Runtime (unchecked) Exception can not be caught during compiling time, but we must handle it with try catch.


IndexOutOfBoundsException is a runtime exception.






Try/Catch/Finally


try {
  // implementation
} catch (ExceptionType name) {
  // handle exception
} catch (ExceptionType name) {
  // handle exception
} finally {
  // always get called
}


or


try {

} catch (IndexOutOfBoundsException e) {
    System.err.println("IndexOutOfBoundsException: " + e.getMessage());
} catch (IOException e) {
    System.err.println("Caught IOException: " + e.getMessage());
} finally {
  // always get called
}



Or

Catching More Than One Type of Exception with One Exception Handler

try {

} catch (IndexOutOfBoundsException | IOException e) {
    System.err.println("IndexOutOfBoundsException or IOException: " + e.getMessage());
} catch (Exception e) {
    System.err.println("Caught Exception: " + e.getMessage());
} finally {
  // always get called
}



or 


try with resources

Note: A resource is an object that must be closed once your program is done using it. For example a File resource or JDBC resource for database connection or a Socket connection resource. Before Java 7, there was no auto resource management and we should explicitly close the resource once our work is done with it. Usually, it was done in the finally block of a try-catch statement. This approach used to cause memory leaks and performance hit when we forgot to close the resource.

The try-with-resources statement is a try statement that declares one or more resources. A resource is an object that must be closed after the program is finished with it. The try-with-resources statement ensures that each resource is closed at the end of the statement. Any object that implements java.lang.AutoCloseable, which includes all objects which implement java.io.Closeable, can be used as a resource.



try(// open resources here){
    // use resources
} catch (FileNotFoundException e) {
 // exception handling
}
// resources are closed as soon as try-catch block is executed.
eg:

Previous resource try/catch

In java 6(we need to open resource and close resource)

try {
  br = new BufferedReader(new FileReader("/Users/test.txt"));
  System.out.println(br.readLine());
} catch (IOException e) {
  e.printStackTrace();
} finally {
  try {
    if (br != null)
      br.close();
    } catch (IOException ex) {
      ex.printStackTrace();
    }
}

In java 7:


try (BufferedReader br = new BufferedReader(new FileReader(
    "/Users/test.txt"))) {  System.out.println(br.readLine());
} catch (IOException e) {
  e.printStackTrace();
}

























No comments:

Post a Comment

java special for collection size, array size, and string size

Size: For Collections (eg: Map, List, etc ): usually it use collection.size(), eg         Map<Character, Integer> map ...