Wednesday, July 7, 2010

Exception Handling in Java (when to use try catch/throw/throws)

Exception Handling is one of the important thing in any programming language. It was made easy in java using run-time error management. People wonder that what is exception? Exception is an event, which occurs during the execution of a program that disrupts the normal flow of program's instructions. Then the next point is why these exceptions arise? Answer to this question is very simple, Exceptions are thrown when a program violate the rules of any programming language or the constraints of the execution environment.

Exceptions are generated in two ways: 1. By Java run time environment 2. Manually generated by code written by a programmer.

A program can handle the exceptions or leave it to the callers of the program or to the default run time exception handler(are called uncaught exceptions).

The first doubt arise is why we use exception handling if there is a default run time exception handler? Becoz there are two benefits: it is easy to fix the error, and second it prevents the program from automatically terminating.

There are four ways to handle exceptions

1. Using try catch block
2. Using Throw
3. Using Throws
4. Using finally


Let me examine each way with simple example and discuss each in detail

1. Try Catch: Try catch is the very simple form to handle exceptions. Enclose the code inside try block to monitor any exceptions. Immediately after try block, include catch block to catch any exceptions thrown in try block as shown in the below example

try
{
//block of code to execute
}
catch(Exception1)
{

}
catch(Exception2)
{

}

Exception1 and Exception2 are type of exceptions thrown by code in try block.

2. Throw: Throw is used when the programmer wants to throw an exception explicitly using Throwable instance not by the java run time environment. More specifically throw is used when the programmer wants to throw his/her own exceptions. Throw statement requires a single argument: throwable object. Flow of execution stops immediately after throw statement; all subsequent statements are not executed.

Example:

class Throw
{
static void hello()
{
try
{
throw new NullPointerException("throw")
}
catch(NullPointerException e)
{
System.out.println(e);
}
}
public static void main(String args[])
{
hello();
}
}

Output of the above program is: java.lang.NullPointerException: throw

Here I'm trying to throw NullPointerException which is a subclass of Exception.

3. Throws: If a callable method is capable of causing an exception that it doesn't handle, it must specify the behavior of the exception so that the callers will handle the exception. In this case we can use throws as shown in the below example.

type method-name(parameter list) throws exception-list
{
//body of method
}

type is the return type of the method, method-name is the name of the method and exception-list is the list of exceptions that a method can throw. If other class methods wants to call this method, it has to handle the exceptions thrown by this method.

4. Finally: When exception occurs, the code after the statement which causes the exception will not be executed. For example, if we open a file and an exception occurs without closing the file, it lead to memory shortage. Finally block is provided to avoid this problem. Code written in finally block is get executed even after the exception arises except when System.exit(0) is used inside try or catch block.

Please refer to this article for more information on finally block

No comments:

Post a Comment