Thursday, February 2, 2012

Exception handeling in Java

What is Exception handeling
Exception are such anomalous conditions (or typically an event) which changes the normal flow of execution of a program. Exceptions are used for signaling erroneous (exceptional) conditions which occur during the run time processing. Exceptions may occur in any programming language or any situation.
Occurrence of any kind of exception in java applications may result in an abrupt termination of the JVM or simply the JVM crashes which leaves the user unaware of the causes of such anomalous conditions. However Java provides mechanisms to handle such situations through its superb exception handling mechanism. The Java programming language uses Exception classes to handle such erroneous conditions and exceptional events. 
Advantage of Exception handling in java.
  • Exception provides the means to separate the details of what to do when something out of the ordinary happens from the main logic of a program. 
  • One of the significance of this mechanism is that it throws an exception whenever a calling method encounters an error providing that the calling method takes care of that error.
  • With the help of this mechanism the working code and the error-handling code can be disintegrated. It also gives us the scope of organizing and differentiating between different error types using a separate block of codes. This is done with the help of try-catch blocks
  • Furthermore the errors can be propagated up the method call stack i.e. problems occurring at the lower level in the chain can be handled by the methods higher up the call chain . 
Exception handling mechanism
try and catch block is used for exception handling purpose. Suspected code are put into try block and it the code generate any error during run time the particular catch block catches the exception. Typical try catch block is something like this.
String myException()
{
try
{
return myMethod();
}
catch ( IOException e )
{
return null;
}
}


Exception class hierarchy
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjbDOxowplWxUahTw2oRqr-fkq6Go7TsKB08LvEJJpVUXOfKyx0yPgoNCtrQnEBUrjsAC8hVovvxYwFP8-w30RnUQhELknLSWIh2EKthPkIFBSSWxD4OvHj86BbF6wG6AE9fltbN1pzdp0/s320/unrecoverable.gif

Types of Exceptions:-
Checked Exceptions - These are some exceptions which occur during the compile time of the program. The compiler checks at the compile time that whether the program contains handlers for checked exceptions or not. These exceptions do not extend RuntimeException class and must be handled to avoid a compile-time error by the programmer. These exceptions extend the java.lang.Exception class  These exceptional conditions should be anticipated and recovered by an application. Furthermore Checked exceptions are required to be caught. Remember that all the exceptions are checked exceptions unless and until those indicated by Error.
Unchecked Exceptions -  Unchecked exceptions are those exceptions which occur during the runtime of the program. Unchecked exceptions are internal to the application and extend the java.lang.RuntimeException that is inherited from java.lang.Exception class. Runtime exception or unchecked exception generates generally data type conversion ,Database connection,Devide by zero and so many similar situation.
Error - The errors in java are external to the application. These are the exceptional conditions that could not be usually anticipated by the application and also could not be recovered from. Error exceptions belong to Error and its subclasses  are not subject to the catch or Specify requirement. Suppose a file is successfully opened by an application for input but due to some system malfunction could not be able to read that file then the java.io.IOError would be thrown. This error will cause the program to terminate but if an application wants then the error might be caught. An Error indicates serious problems that a reasonable application should not try to catch. Most such errors are abnormal conditions.


some simple program of exception handeling

Catching Arithmetic Exception

public void callDivide(){
        try {
               int num=0;
            int result =10/num;
            System.out.println(result);
            }
            catch (ArithmaticExceptions e)
            {
            //do something clever with the exception
            System.out.println(e.getMessage());
            }
            System.out.println("Division attempt done");
    }
In this program one arithmetic exception will generate and the catch block will catch the exception.

Catching I/O Exception.
public void openFile(){
        try {
            // constructor may throw FileNotFoundException
            FileReader reader = new FileReader("someFile");
            int i=0;
            while(i != -1){
                //reader.read() may throw IOException
                i = reader.read();
                System.out.println((char) i );
            }
            reader.close();
            System.out.println("--- File End ---");
        } catch (FileNotFoundException e) {
            //do something clever with the exception
        } catch (IOException e) {
            //do something clever with the exception
        }
    }




No comments:

Post a Comment