Friday, 31 May 2013

2. Exceptions in JAVA

Following are the methods of Exception class:
  • public String getMessage():Returns a detailed message about the exception that has occurred. This message is initialized in the Throwable constructor.
  • public Throwable getCause():Returns the cause of the exception as represented by a Throwable object.
  • public String toString():Returns the name of the class concatenated with the result of getMessage()
  • public void printStackTrace():Prints the result of toString() along with the stack trace to System.err, the error output stream.
  • public StackTraceElement [] getStackTrace():Returns an array containing each element on the stack trace. The element at index 0 represents the top of the call stack, and the last element in the array represents the method at the bottom of the call stack.
  • public Throwable fillInStackTrace():Fills the stack trace of this Throwable object with the current stack trace, adding to any previous information in the stack trace.
Catching Exceptions:
A method catches an exception using a combination of the try and catch keywords. A try/catch block is placed around the code that might generate an exception. Code within a try/catch block is referred to as protected code, and the syntax for using try/catch looks like the following:

try
{
   //Protected code
}catch(ExceptionName e1)
{
   //Catch block
}

A catch statement involves declaring the type of exception you are trying to catch. If an exception occurs in protected code, the catch block (or blocks) that follows the try is checked. If the type of exception that occurred is listed in a catch block, the exception is passed to the catch block much as an argument is passed into a method parameter.

Example1:
public class TryCatchExample {

/**
 * @param args
 */
public static void main(String[] args) {
int[] a = new int[] { 9, 8, 7 };
try {
/**
  * Here we have array a of size 3. But in for loop we are 
   * trying to access 4th element of an array(for loop continues 
   * 4 times from i value 0 to 3). so here we got exception 
   * array out of bounds exception.
 */
 for (int i = 0; i < 4; i++) {
   System.out.println("element at index " + i + " is " + a[i]);
  }
catch (ArrayIndexOutOfBoundsException e) {
 /**
 * Here we know may got ArrayIndexOutOfBoundsException 
    * so we have used exception of type ArrayIndexOutOfBoundsException in 
    * catch block. If we do  not know what type of exception we may got then 
    * we should use Exception. because exception is superclass for all 
    * exception types.So see the below example. It also catch the exception.
 */
e.printStackTrace();
}
    }
}

Output:
element at index 0 is 9
element at index 1 is 8
element at index 2 is 7
java.lang.ArrayIndexOutOfBoundsException: 3
at om.sample.javase.testing.TryCatchExample.main(TryCatchExample.java:18)

Example2:

public class TryCatchExample2 {

/**
 * @param args
 */
public static void main(String[] args) {
int[] a = new int[] { 9, 8, 7 };
try {
for (int i = 0; i < 4; i++) {
       System.out.println("element at index " + i + " is " + a[i]);
}
catch (Exception e) {
 /**
 * Here we know may got ArrayIndexOutOfBoundsException 
    * so we have used exception of type ArrayIndexOutOfBoundsException in 
    * catch block. If we do  not know what type of exception we may got then 
    * we should use Exception. because exception is superclass for all 
    * exception types.
 */
e.printStackTrace();
}
}
}

Output:
element at index 0 is 9
element at index 1 is 8
element at index 2 is 7
java.lang.ArrayIndexOutOfBoundsException: 3
at om.sample.javase.testing.TryCatchExample.main(TryCatchExample.java:18)

But it is not recommended to use Exception type in all scenarios like above Example2 because programmer will definitely knows about the exception which may occurred. Please write specific type of exception for best exception handling like above Example1.

Multiple catch Blocks:

A try block can be followed by multiple catch blocks. The syntax for multiple catch blocks looks like the following:

try
{
   //Protected code
}catch(ExceptionType1 e1)
{
   //Catch block
}catch(ExceptionType2 e2)
{
   //Catch block
}catch(ExceptionType3 e3)
{
   //Catch block
}

We can have any number of them after a single try. If an exception occurs in the protected code, the exception is thrown to the first catch block in the list. If the data type of the exception thrown matches ExceptionType1, it gets caught there. If not, the exception passes down to the second catch statement. This continues until the exception either is caught or falls through all catches, in which case the current method stops execution and the exception is thrown down to the previous method on the call stack.

Example1:
public class TryWithMultipleCatch1 {

/**
 * @param args
 */
public static void main(String[] args) {

try {

File file = new File("filename");
FileOutputStream fileOutputStream = new            
                        FileOutputStream(file);
// please write own logic here which throws FileNotFoundException.
/**
 * Here we may get FileNotFoundException if file does not exists. So first 
    * catch block catches the exception. So second and third catch block is not 
    * valid. So becarefull while writing multiple catch blocks. If we got other 
    * than the FileNotFoundException,like 
    *ArrayIndexOutOfBoundsException, then exception is caught in second 
    * catch block. If we did not get both ArrayIndexOutOfBoundsException, 
    * FileNotFoundException, then exception is caught by third catch block 
    * catches the  exception.
 */
catch (FileNotFoundException e) {
e.printStackTrace();
System.out.println("called");
catch (ArrayIndexOutOfBoundsException e) {
e.printStackTrace();
System.out.println("not called");
catch (Exception e) {
e.printStackTrace();
System.out.println("not called");
}
}
}

Example2:
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.nio.file.FileAlreadyExistsException;

public class TryWithMultipleCatch2 {

/**
 * @param args
 */
public static void main(String[] args) {

try {

File file = new File("filename");
FileOutputStream fileOutputStream = new FileOutputStream(file);
// please write own logic here which throws any type of Exception.
catch (Exception e) {
       /**
        * Any type of exception can be caught here. Because here we are using
Exception type for this catch block. It is super class of all
* exception types. So it is does not allow us to write any other
* catch blocks followed by this catch block because it catches any type   
        * of exception here only.
*/
e.printStackTrace();
System.out.println("called");
catch (ArrayIndexOutOfBoundsException e) { // not allowed this catch block
e.printStackTrace();
System.out.println("not called");
catch (FileNotFoundException e) { // not allowed this catch block
e.printStackTrace();
System.out.println("not called");
}
}
}

Note: Please observe the second/above example. We write first catch block with type Exception. So if we got any exception, then it should catch in first catch block only. So in above program  second and third catch block does not allow to write. SO while using multiple catch blocks , please write exact exception types which we may got. or else if we write Exception type in catch block then it does not allow to write other/multiple catch blocks. Because Exception is super class of all exception types.

"Please remember, first need to write sub level exceptions in ascending order for writing multiple catch blocks".

But it is not recommended to use Exception type in all scenarios like above Example2. Please write specific type of exception for best exception handling like above Example1.

Will continue exceptions in next post 3.Exceptions in JAVA.

No comments:

Post a Comment