Let's explore java

Monday, August 01, 2011

Exception handling

First of all we should learn that what exception exactly means? Exceptions are the events occured by the java run time system or the user programmer which disrupts the normal flow of the program.
Java run time system implements a technique called exception handling which examines the program for the correct execution of the program.Exception handling is the method when if any problem occures in the programming then the execution disrupts and the cause of the exception are being displayed.Throwable is the main built in class for all other subclasses of the exception.
Throwable-->Exception-->RuntimeException....this is the class hierarchy how the exception classes works.
Suppose any perticular programming shows the runtime exception and user did not explictly implemented the exception handler then java run time system implements default exception handler.
The program will explain you in the best possible way.

class default {
public static void main(String args[]) {
int d = 0;
int a = 42 / d;
}
}
Here in this program when java run time system finds that there is an attempt to divide by zero then it creats the exception object and throws the exception.When the exception has been thrown the execution ofthe program stops because once the exception has been thrown it must be caught by a exception handler defined by user.Here what we find that there is no any exception handler by the user so java run time system creates the default exception handler which catch this exception and displays the string describing about the exception.Here is the output when this program is being executed:-
java.lang.ArithmeticException: / by zero
at default.main(default.java:4)
Although java's default handler is the good way to debug and fix the problem occured in the program but sometime user himself wants to fix the problem by using explictly exception handler.There are two benifits when explicetly defining the exception handler.
1)you can fix the problem in the most easiest way.
2)you can prevent the program from terminating .
To guard and debugg against the run time exception just embed the programming with try block which throws the exception whenever it occures and at the end there must be catch statement which catches the exception and debugging starts.
This is the general form of an exception-handling block:
try {
// block of code to monitor for errors
}
catch (ExceptionType1 exOb) {
// exception handler for ExceptionType1
}
catch (ExceptionType2 exOb) {
// exception handler for ExceptionType2
}
we will continue from here in the next blog post.
thank you for your devotion towards java....hava a nice day...

1 comment: