BIG
DATA

JAVA

Exception handling in Java

Read more about »
  • Java 9 features
  • Read about Hadoop
  • Read about Storm
  • Read about Storm
 

This article describes how to write an exception handler.

What is Exception Handling?

An exception is an event that occurs during the execution of a program that disrupts the normal flow of instructions. The exception handling in java is the mechanism to handle the exception so that normal flow of the application can be maintained.

Why to handle exception?

If an exception is raised, and if there is no exception handler to handle that exception then program execution can get terminated and system prints a non user friendly error message like below:

Exception in thread "main" java.io.IOExceptionn: file not found at CoreJavaGuruDemo.main(CoreJavaGuruDemo.java:12)
 CoreJavaGuruDemo : The class name
 main : The method name
 CoreJavaGuruDemo.java : The filename
 java:12 : Line number
 

How to handle exception?

Exception handling is done by transferring the execution of a program to an appropriate exception handler when exception occurs. Exceptions can be handled by using 'try-catch' block. Java provides specific keywords for exception handling purposes:

  • try
  • catch
  • throw
  • throws
  • finally

The try Block

The try block contains a block of program statements within which an exception might occur. Hence the first step in constructing an exception handler is to enclose the code that might throw an exception within a try block.

try {
    code
}
catch and finally blocks . . .

You can put each line of code that might throw an exception within its own try block and provide separate exception handlers for each. Or, you can put all the writeList code within a single try block and associate multiple handlers with it. The later is more cleaner way of coding.

If an exception occurs within the try block, that exception is handled by an exception handler associated with it. To associate an exception handler with a try block, you must put a catch block after it. A try block must followed by a Catch block or Finally block or both.

The catch Blocks

Once a try block is put, a catch block must be associated with it to handle exceptions. The corresponding catch block executes if an exception of a particular type occurs within the try block. You can associate one or more catch blocks directly after the try block. And no code can be between the end of the try block and the beginning of the first catch block.

try {

} catch (ExceptionType name) {

} catch (ExceptionType name) {

}

Each catch block is an exception handler that handles the type of exception indicated by its argument. The argument ExceptionType, declares the type of exception that the handler can handle and must be the name of a class that inherits from the Throwable class.

If an exception occurs in protected code that is inside the try block, the catch block (or blocks) that follows the try is checked. If the type of exception that occurred is listed in a catch block, the exception is passed to the catch block much as an argument is passed into a method parameter. The catch block contains code that is executed if and when the exception handler is invoked.

Java SE 7 and later

In Java SE 7 and later, a single catch block can handle more than one type of exception. In the catch clause, specify the types of exceptions that block can handle, and separate each exception type with a vertical bar (|).This feature can reduce code duplication and lessen the temptation to catch an overly broad exception.

catch (IOException|SQLException ex) {
    ......
}

The finally Block

You can attach a finally-clause to a try-catch block or just a try block. The finally block always executes when the try block exits. This ensures that the finally block is executed even if an unexpected exception occurs.The code inside the finally clause will always be executed, even if an exception is thrown from within the try or catch block. If your code has a return statement inside the try or catch block, the code inside the finally-block will get executed before returning from the method.

But finally is useful for more than just exception handling — it allows the programmer to avoid having cleanup code accidentally bypassed by a return, continue, or break. Putting cleanup code in a finally block is always a good practice, even when no exceptions are anticipated. The finally block is a key tool for preventing resource leaks. When closing a file or otherwise recovering resources, place the code in a finally block to ensure that resource is always recovered.

finally {
	......
}

The try-with-resources Statement

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

try (BufferedReader br =
	new BufferedReader(new FileReader(path))) {
	....
	....
}

A try-with-resources statement can have catch and finally blocks just like an ordinary try statement. In a try-with-resources statement, any catch or finally block is run after the resources declared have been closed.

Suppressed Exceptions

An exception can be thrown from the try block, and also exceptions can be thrown from the try-with-resources statement. If an exception is thrown from the try block and one or more exceptions are thrown from the try-with-resources statement, then those exceptions thrown from the try-with-resources statement are suppressed, and the exception thrown by the block is the one that is thrown. You can retrieve these suppressed exceptions by calling the Throwable.getSuppressed method from the exception thrown by the try block.

Advantages of Exception Handling

  • Exception handling allows us to control the normal flow of the program by using exception handling in program.The execution of a Java program does not terminate when an exception occurs. Once the exception is resolved, program execution continues till completion.
  • The logic in the program code does not include details of the actions to be performed when an exception occurs. Such details are present in the catch blocks. Thus Exception Handling segregates error-handling code and program code making it easier to identify the logical flow of a program.
  • Advantage of Exception Handling is the ability to propagate error reporting up the call stack of methods. Java runtime searches backward through the call stack to find any methods that are interested in handling a particular exception. A method can duck any exceptions thrown within it, thereby allowing a method farther up the call stack to catch it. Hence, only the methods that care about errors have to worry about detecting errors.
  • Traditional programming languages use error codes for error reporting which makes it very complex to debug in the case of large programs. Java’s exception handling mechanism provides meaningful descriptions which is helpful when you are debuging large programs.
    catch (ArithmeticException e) {
        System.out.println("Exception occurred: " + e);
    }
    When an arithmetic exception occurs following is displayed:
    Exception occurred: java.lang.ArithmeticException: / by zero
  • Java provides several super classes and sub classes that group exceptions based on their type. While the super classes provide functionality to handle exceptions of a general type, sub classes provide functionality to handle specific exception types.A method can catch and handle a specific exception type by using a sub class object. In case a method needs to handle multiple exceptions that are of the same group, you can specify an object of a super class in the method’s catch statement.