Tuesday, June 21, 2016

Re-throwing an Exception Example Java

What is the difference between throws and throw?

Ans: throws clause is used when the programmer does not want to handle the exception and throw it out of a method.throw clause is used when the programmer wants to throw an exception explicitly and wants to handle it using catch block.Hence throw and throws are contradictory.

Re-Throwing an Exception

When an exception occurs in a try block it is caught by a catch block.This means that the thrown exception is available to the catch block .eg.

try
{
   thrown exception;
}
catch(Exception e)
{
 thrown exception;   // re-throw the exception out
}

Program:

/**
 *
 */
package com.collectionpack;

/**
 * @author Abhinaw.Tripathi
 *
 */

class A
{
void method()
{
try
{
String str="Hello";
char ch=str.charAt(5);
}
catch (Exception e)
{
System.out.println("Please see the index is within the range");
throw e;
}
}

}

public class ReThrowingExceptionApp
{
/**
* @param args
*/
public static void main(String[] args)
{
A a=new A();
try
{
a.method();
}
catch (Exception e)
{
e.printStackTrace();
System.out.println("I caught re-thrwon exception");
}
}


}

Output:

Please see the index is within the range
java.lang.StringIndexOutOfBoundsException: String index out of range: 5
at java.lang.String.charAt(Unknown Source)
at com.collectionpack.A.method(ReThrowingExceptionApp.java:18)
at com.collectionpack.ReThrowingExceptionApp.main(ReThrowingExceptionApp.java:39)
I caught re-thrwon exception


Is it possible to re-throw exceptions?

Ans: Yes,it is,re-throw an exception from a catch block to another class where it can handled.

No comments: