Skip to main content

Exception Handling

Exception

Unexpected situation, occurs during program execution where further execution is possible

By default, JRE will handle the exception & exit the program execution safely. User can also handle exception manually using try/catch/throw/finally mechanism

Exception Types

Checked Exception

Checked exceptions are checked at compile-time

If a method is throwing a checked exception then it should handle the exception using either try-catch block or it should declare the exception using throws keyword

E.g. FileNotFoundException, IOException

Unchecked Exception

Unchecked exceptions are not checked at compile-time rather they are checked at runtime

All unchecked exception extends RuntimeException class

E.g. ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException

Exception Handling

Exception handling is done using try/catch/finally mechanism or using throws keyword

try - contains a block of program statements within which an exception might occur. try can be followed by either one or more catch block or finally block or both

catch - each catch block is an exception handler that handles the type of exception indicated by its argument

finally - finally block will be called, irrespective of exception occurred or not. Usually resource cleanup operations are performed here

try {

} catch (IndexOutOfBoundsException e) {
System.out.println("IndexOutOfBoundsException: " + e.getMessage());

} catch (IOException e) {
System.out.println("Caught IOException: " + e.getMessage());
}

throws - throws keyword used to declare an exception (usually checked exception) in method signature. throws keyword propagate the exception (if occurred) to the caller method. If we use throws keyword, we can skip the try/catch mechanism.

E.g. void display() throws IOException {

}

throw - throw keyword is used to explicitly throw an exception.

E.g. throw new ArithmeticException()