Wednesday, September 5, 2012

Exception Handling in Java


Whenever we write a code we need to take care of several path of execution but sometimes it's   impossible to take care of all the probabilities,so when the code run through these unhandled paths we may have to face exception in normal execution.
In Java to avoid these kind of scenario we use Exception handling mechanisms.







Suppose method1() calls method2()
               method2() calls method3()
               method3() calls method4()

Here if any error occurs in method4() then an Exception object is created and throws it back to the method which called means here it is method3() then back to method2() and method1().
This Exception objects some information of the error occurred like error code,cause,line number etc
The Object is thrown so that the calling method can get a chance to handle it and keep going with the normal  flow of program execution.
The call stack mechanism of exception handling is a very useful feature in Java.

There are three types of exception

Checked Exception :
 Except the Error and Runtime Exception all exceptions are checked exception. Suppose we write a program to read an image file so the image path is also mentioned in the program.Now if the image doesn't exist on the path we  will get an Exception of java.io.FileNotFoundException.So we have to handle this Exception.The method responsible for reading the image throws an Exception of  java.io.FileNotFoundException while the file doesn't exist .We need to handle all the Exceptions before compilation.If we don't handle this then we get a compilation error for not handling the checked Exceptions.Checked Exception are predictable Exception so it's easy to handle them.

Runtime Exception :
This type of  Exceptions occurs generally because of  error in programming logic.
Suppose you are trying to cast an Non Integer Object into an  Integer here Casting is not possible so you will get an Exception as ClassCastException.
Runtime exceptions are not predictable at the time of compilation.
This exception is considered as unchecked Exception.
Some very common runtime exceptions are ArrayIndexOutOfBoundException, NullPointerException.

Error :
This type of Exception is completely out of scope of the application.A programmer cannot make this type of Exception.Error happens due to some external reason like you are trying to add too many objects in memory but JVM memory MAX limit size is already reached so you will get an error  named  java.lang.OutOfMemoryError.
Common error is  java.lang.NoClassDefFoundError.


Exception Hierarchy





Handling Exception
In Java we used to handle exception using try{} block  which is followed by a catch(){} and/or a finally{} block.
try
{
  // add code here
} catch(exception name)
{

   // handle in catch block
}finally
{

  // handle inside finally
}


 Exception can be handled in catch() block then why do we need the finally block ?
 If any exception occurs then try block is not executed till the end so it goes to the catch block and if no exception occurs then the catch() block is not executed so what will we do if we need to execute for both the situation. Like connection release or file release kind of thing must be executed so we generally put these type of operations in finally  block as finally block should always be executed.

We can put multiple catch block for a single try block as the try block can throw multiple Exceptions so to handle each of the Exceptions we can add different catch block.

Let us discuss about few common Exceptions


java.lang.ArrayIndexOutOfBoundsException :   This Exception is thrown while trying to get the value of index out side the range of   0  to  (length -1)  range.
Example Code :
public void arrayException() {
  int[] intArray = new int[] { 1, 5, 6, 9, 0 };

  System.out.println("size of Array is " + intArray.length);
  System.out.println("1 st element is  " + intArray[0]);
  System.out.println("5 th element is  " + intArray[4]);
  System.out.println("Let us check the 6 th element ?  " + intArray[5]);

 }

Output :
size of Array is 5
1 st element is  1
5 th element is  0
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
 at com.fastlearned.ExceptionExample.arrayException(ExceptionExample.java:11)
 at com.fastlearned.ExceptionExample.main(ExceptionExample.java:49)


java.lang.StringIndexOutOfBoundsException : This Exception is thrown while trying to get  the character of a string value of index outside 0 to length()-1 range

Example Code :
public void stringException() {
  String str = "fastLearned";

  System.out.println("size of str is " + str.length());
  System.out.println("13 st element is  " + str.charAt(12));

 }

Output :
size of str is 11
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 12
 at java.lang.String.charAt(String.java:687)
 at com.fastlearned.ExceptionExample.stringException(ExceptionExample.java:19)
 at com.fastlearned.ExceptionExample.main(ExceptionExample.java:50)


java.lang.NullPointerException : This Exception is thrown while an object in not initialized but we started working on it.

Example Code :
public void nullstringException() {
  String str = null;
  System.out.println("size of str is " + str.length());

 }

Output :
Exception in thread "main" java.lang.NullPointerException
 at com.fastlearned.ExceptionExample.nullstringException(ExceptionExample.java:25)
 at com.fastlearned.ExceptionExample.main(ExceptionExample.java:51)



java.lang.NumberFormatException : This Exception happens when we try to convert wrong  string 
into number like trying to convert a alphabet into a number or a float into a int.

Example Code :
  public void numberFormatTestException()
 {
  int intVal = Integer.valueOf("8.9");
 }

Output :
Exception in thread "main" java.lang.NumberFormatException: For input string: "8.9"
 at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
 at java.lang.Integer.parseInt(Integer.java:456)
 at java.lang.Integer.valueOf(Integer.java:553)
 at com.fastlearned.ExceptionExample.numberFormatTestException(ExceptionExample.java:31)
 at com.fastlearned.ExceptionExample.main(ExceptionExample.java:52)


 java.lang.OutOfMemoryError :

This error can be thrown if you run out of memory:
This error is thrown by the JVM when new object can be created in it's memory.

java.lang.StackOverflowError :
Each process is allocated a fixed size stack and a stack is used to store the activation record of each method that is called it contains the parameters and the local variables as well as other information such as the return address. Unbounded recursion can cause the Java Virtual Machine to run out of space in the stack:


Example Code :
  public void methodA()
 {
  methodB();
 }

 private void methodB() {
  methodA();
  
 }
 

java.lang.NoClassDefFoundError : Java Interpreter throws this Error.This is thrown when The Class we are trying to run is not accessible from the working directory.
It can be due to package structure also like while running the Class we forget to mention the package name before the Class .

java.lang.NoSuchMethodError : This Error is thrown at runtime while trying to call a method which doesnot exist.If you don't put a main method and trying to run the class you get this error.If you made a change in the signature of main method then also you will get this Error.

No comments:

Post a Comment