My Profile
Active Members
TodayLast 7 Days
more...
Awards & Gifts
Online Exams
Fresher Jobs
Our fresher job section is exclusively for fresh graduates! Find jobs for freshers in major Indian
cities including Bangalore, Chennai, Hyderabad, Pune or Kochi
Resources
Find educational articles, blogs, discussion threads and other resources.
Colleges
Find details about any college in India or search for courses.
|
Resources » Articles/Knowledge Sharing » Computer & Technology »
Exception Handling in Java
|
The term exception is shorthand for the phrase "exceptional event". An exception is an event, which occurs during the exception of a program, which disrupts the normal flow of the program's instructions. When an error occurs within a method, the method creates an object and hands it off to the run time system. The object, called an exception object, contains information about the error, including its type and the state of the program when the error occurred. Creating an exception object and handling it to the run time system is called 'throwing an exception'. The The run time system searches the call stack for a method that contains a block of code that can handle the exception. This block of code is called an 'exception handler'. The search begins with the method in which the error occurred and proceeds through the call stack in the reverse order in which the methods were called. When an appropriate handler is found, the run time system passes the exception to the handler. An exception handler is considered appropriate if the type of the exception object thrown matches the type that can be handled by the handler. The exception handler chosen is said to catch the exception. If the run time system exhaustively searches all the methods on the call stack without finding an appropriate exception handler, the run time system terminates.
AN EXAMPLE WITH EXCEPTION HANDLING:
public class printsquare1{ public static void main(String[] args){ BufferedReader in =new BufferedReader(new InputStreamReader (System.in)); double d; String doubleStr; System.out.print("Enter double"); doubleStr=in.readLine(); d=Double.parseDouble(doubleStr); System.out.println("The square is:"+ d*d); } } The above program when compiled, results in an error: unreported exception java.io.IOException; must be caught or declared to be thrown. The error is due to the reason that, the method readLine() specifies that it throws the said exception. It is a checked exception and hence it should be handled. Checked exceptions should abide by the Catch or Specify requirement. If a method has code that results in checked exceptions, either the method should provide the handler or specify that it in turn throws that exception, so that the caller method is responsible. Another example of such exception is InterruptedException thrown by Thread.sleep() method. The following are corrected versions of the program:one with catch requirement, and another with specify requirement. The program also adds another handler to take care of the error that the user may enter invalid double string like 23$.56. In such case, the method Double.parseDouble() throws an NumberFormatException as it will be unable to convert such string to a valid Double value. However, NumberFormatException is an unchecked exception. It is not mandatory that it should be handled. The third kind of exceptions is Error exceptions. These are thrown, when a system violation takes place like running out of memory during exception, trying to load a class not found.
public class printsquare{ public static void main(String[] args){ BufferedReader in = new BufferedReader(new InputStreamReader (System.in)) ; double d; String doubleStr; System.out.println("Enter a double value:"); try{ doubleStr in=readLine(); d=Double.parseDouble(doubleStr); System.out.println("Square is:"+ d*d); } catch(IOException e){ System.out.println(e.getMessage()); } catch(NumberFormatException e){ System.out.println(e.getMessage()); } } }
All the language defined exception classes are subclasses of the super class Throwable. When an Exception occurs, the "thrown" entity is an object. The object can carry information from the point where the exception occurs to the point where it is caught and handled. This information always includes an error message describing what happened to cause the exception, and it can contain other data as well. The object thrown by an exception must be as instance of the standard class java.lang.Throwable or of one of its subclasses. In general, each different type of exception is represented by its own subclass of Throwable. In addition, a programmer can create new exception classes to represent new types of exceptions. getMessage() and printStackTrace() are the two important methods provided by the Throwable class to print the diagnostic message of the exception and the chain of method invocations that lead to the exception.
The classes derived from Exception represent Checked Exceptions. The classes derived from RuntimeException represent unchecked exception. The classes derived from Error represent Error exceptions. Examples for error exceptions are OutOfMemoryError,ClassDefNotFoundError, StackOverFlowError, IOError etc. Coding a handler: The first step in constructing an exception handler is to enclose the code that might throw an exception within a try block. In general, a try block looks like the following. You associate exception handlers with try block by providing one or more catch blocks directly after the try block. No code can be between the end of the try block and the beginning of the first catch block.
try{ //code that is expected to throw exception(s) } catch(ExceptionType name){ //handler } catch(ExceptionType name){ //handler } . . . finally{ //finally block }
Each catch block is an exception handler and handles the type of exception indicated by its argument type. ExceptionType, declares the type of the exception that the handler can handle and must be the name of a class that inherits from the Throwable class. The handler can refer to the exception with name. The catch block contains code invokes the exception handler is the first one in the call stack whose Exception Type matches the type of the exception thrown. The system considers it a match if the thrown object can legally be assigned to the exception handlers argument. The run time system always executes the statements within the finally block regardless of what happens within the try block. So it's the perfect place to perform cleanup.
Throwing Exceptions: Before you can catch an exception, some code somewhere must throw one. Any code can throw an exception: our code, code from a package written by someone else such as the packages that come with the java platform or the java run time environment. Regardless of what throws the exception its always thrown with the 'throw' statement. All the exception classes are descendants of the Throwable class and all allow programs to differentiate among the various types of exceptions that can occur during the execution of a program.
|
Responses
|
No responses found. Be the first to respond and make money from revenue sharing program.
|
|
Advertise Here
|