Saturday, August 16, 2014

Java Exception Handling

Exception as the name suggests is about situations that are not expected in normal processing. Exception handling in Java deals with the area of handling not normal conditions. For example you have logic to divide a by b but what happens if b is 0. You can put a check beforehand that proceed if b is not zero. This is a trivial situation. In real life there might be more than one scenario where you cannot proceed with normal logic. So what you do - Put a lot of if clause before the actual logic is invoked. This clutters the program and also you write more code for handling abnormal conditions than handling the normal logic flow.To solve such kind of situation, the whole notion of Exception Handling has evolved.
Java is a pure object oriented language. In the true spirit, Exceptions in Java are also represented by objects. So in the case of division of a by b, if b is zero an object is thrown which represents that this division is not possible. In this case the program will throw ArithmeticException.
If you want to handle this exception than the code to handle is 
try{

   c= a/b;

}catch(ArithmeticException ae){
        //do Something to handle exception

}finally{
    //This block is called even if exception is thrown or not
}

If you donot catch the exception here, the exception is thrown all the way up to the calling programs. If no one in the application catches the exception, the exception is returned to the main program and in turn is printed on the console. There are three kind of exceptions which are:
  • Checked Exceptions: These are exceptions which the user are forced to handle, either by catching it or rethrowing it.For example in database connection, you are forced to catch SQLException. Checked exception subclass from java.lang.Exception.
  • Error: These exceptions are external to application and usually difficult to control.Error exceptions subclass from java.lang.Error.
  • Runtime Exceptions: Runtime Exceptions are related to application logic. For example NullPointerException. Runtime Exceptions subclass from java.lang.RuntimeException.
Error and Runtime Exceptions are also known as Unchecked exceptions as these exceptions do not force programmers to handle them.
Writing Exception

An exception is written by deriving it from proper subclass. To write a checked exception derive it from java.lang.Exception 
public class MyException extends Exception{
      public MyException(String msg){
           super(msg);
     }

//It's always a good practice to wrap the earlier exceptions, if you are throwing yours.
//The will provide the end user a better insight into the problem
public MyException(String msg, Throwable t){
       super(msg,t);
  }
}

Best Practices to Handle Exception

  • Checked and Unchecked Exception: Decide carefully which exception you want to use. A thumb rule is that if Client can do something reasonable to handle the exception and recover from it than used Checked Exception, other wise use Unchecked exception. The current trend is to move toward Unchecked exceptions and it is left to the discretion of the client to how to handle that.
  • Wrap the Exception: When you catch an Exception and throw your own exception than make sure you wrap up the catched exception in your exception and than throw it.
try{
}catch(SQLException se){
          throw new MyException(se);
          //Do not just say throw new MyException();
}

  • Use finer Exception hierarchy: Do not throw and catch Exception, the root class. Develop finer hierarchy which represent the exceptional conditions appropriately. However be careful to not to develop so finer, that your application has more kind of exceptions than application logic class. Strive the balancing act.

No comments:

Post a Comment