Search This Blog

Tuesday, 4 October 2011

Exception handling in Java

0 comments
Exception Handling in Java
An exception is an abnormal condition that many arise from a code sequence at run time. Exception handling is a mechanism provided in programming languages like C++ and Java for handling the exception that may arise during the execution of a program. In other words, an exception is a run-time error. In computer languages that do not support exception handling, errors must be checked and handled manually – typically through the use of error codes.
How Exceptions are handled in Java?
In Java, exceptions are handled using objects of type Exception. An exception in Java is an object that describes the exceptional (i.e. error) condition that may arise from a piece of code. When an exceptional condition occurs, an object representing that exception is created and thrown from the method that caused the error. Thrown exceptions are caught by a special piece of code, called catch block, in order to take remedial action for the particular error condition.
Generally, exceptions are raised from the code that violates the rules of the language or the constraints of the run-time environment of the language. Exceptions are raised implicitly by Java run-time system or explicitly (manually) by a piece of code. Manually generated exceptions are typically used to report some error condition to the caller of a method.
Exception Types:
Exceptions that can be handled in Java are defined in a hierarchy of classes, called Exception classes. All exception classes are subclasses of the built-in class Throwable. Thus, Throwable is at the top of the exception class hierarchy. Immediately below Throwable are two sub classes namely Exception and Error. These two classes define the two major classifications of exception. The class Exception defines all exceptions that can be handled by the user from the code; whereas, the Error class defines the exceptions that are not expected to be caught under normal circumstances.
Exceptions of type Error are used by Java run-time system to indicate the errors that can be handled only by run-time environment. Stack overflow is an exception of type Error. There is an important subclass of Exception, called RunTimeException, which is used for handling exceptions that include division by zero and invalid array indexing.
Five Keywords:
Java exception handling mechanism provides five keywords for handling exceptions, namely try, catch, throw, throws and finally. The keyword try is used for defining a block of code that contains one or more statements, which will be monitored by the run-time system for exceptions. If an exception occurs during the execution of a try block, such exceptions are thrown to the catch block by run-time system.
System generated exceptions are automatically thrown by the Java run-time system. To manually throw an exception, use the keyword throw. Thrown exceptions are handled in a Java program using a block of code called catch block.
Any exception that is thrown out of a method must be specified in the header part of the method using throws clause. Any code that must be executed before a method returns is put in a finally block. The general form of an exception handling block is shown below:
try{
//block of code to be monitored for errors
}
Catch(ExceptionType1 exob) {
// exception handler for ExceptionType1
}
Catch(ExceptionType2 exob) {
// exception handler for ExpcetionType2
}
Finally{
// block of code to be executed before try block ends
}
Here, the ExpceptionType is the type of the exception that has occurred. Any exception that is not caught by the program will ultimately be processed by the default handler. The default exception handler displays a string describing the exception, prints a stack trace from the point at which the exception occurred, and the program terminates. In order to avoid such abrupt termination of a Java program, we need to handle the exception properly.
Using try and catch Blocks:
To guard a block of code against run-time error during its execution, simply enclose that code inside the try block. Next to the try block, include a catch block along with a parameter that specifies the exception type of the exception to be handled. The following program illustrates the use of try block along with a catch block which process the exception named ArithmeticException generated due to division-by-zero error:
Class ExceptHandle{
Public static void main(String args[])
{
Int d, a;
try{ // monitor a block of code
d = 0;
a = 42 / d;
System.out.println(“This will not be printed…”);
}
Catch(ArithmeticException e) {
System.out.println(“Divison by Zero occurred…”);
}
System.out.println(“Exception resumes here…”);
}
}
This program will generate the following output:
Division by Zero occurred…
Execution resumes here…
In the above example, the statement
a = 42 / d;
results in a division-by-zero error, which throws the exception ArithmeticException to Java run-time system. In response, Java run-time system will transfer the program control from the try block to the catch block, which has the object of type ArithmeticException as its parameter. After the execution of catch block, the program control will be transferred to the next statement that follows the entire try/catch block. That means, the control will never return back to the try block for the execution of remaining statements in the try block. That is why the above program prints two lines of output.
A try and its corresponding catch block form a unit. In some cases, more than one exception could be raised by a single try block. To handle such situation, we need to define two or more catch blocks, each catching a different type of exception. All the catch blocks that follow a single try block are considered as a single unit. And each catch block is associated with only one try block, which immediately precedes the catch block(s).
When an exception is thrown, each catch block is inspected in order, and the first exception whose type matches the type of the exception being thrown is selected for execution. After its execution, the program control transfers to the next statement that follows the entire try/catch block, bypassing all the remaining catch blocks associated with the try block.
Displaying the Error Message:
Every exception is an object of type String, which contains the description of the exception that occurred. We can display the description of the exception being raised by passing the exception object as an argument to the println method. The following piece of code illustrates this:
Catch(ArithmeticException e) {
System.out.println(“Exception: ” + e);
a = 0;
}
When an exception of type ArithmeticException is thrown, the above catch block will display the following error message:
Exception: java.lang.ArithmeticException; /by zero
The ‘finally’ block:
The keyword ‘finally’ is used to create a block of code that will be executed after the execution of a try/catch block and before proceeding further for executing the code that follows the try/catch block. This block of code will be executed whether or not an exception occurs from within the try block. If an exception occurs, the finally block will be executed after handling the exception. This block will be executed even if there is no exception handler (catch block) provided for the exception being raised.
The finally block is optional. However, each try statement requires at least one catch or a finally block for handling the error. This block of code is useful for closing file handles and freeing up any other resources that might have been allocated at the beginning of a method of a method with the intent of disposing them before its return.

Leave a Reply