Why rethrow an Exception in Java?

What is rethrowing an Exception

When an Exception is thrown from your code,
1. You can handle handle the Exception completely, by using try and catch blocks you handle the Exception, and further throw the Exception object. OR
2. Use throws with method declaration, to indicate that invokers of the method need to handle the Exception, or further throws it.

Another option we have here is a combination of above both. That is, the Exception is handled, with try, catch blocks, and further throw the Exception.

Below is an example, of the same.

class TDemo22{
	public void met2() throws Exception
	{
	try
	{
	String str="2abcd3";

	int i = Integer.parseInt(str);
	}
	catch(Exception ep)
	{
	System.out.println("Exception catching");
	throw ep;
	}
	}
}

public class NumberFormatDemo {
	public static void main(String args[])
	{
	try{
	TDemo22 td2 = new TDemo22();
	td2.met2();

	}catch(Exception e)
	{
	e.printStackTrace();
	}
	}
}

There are two different ways, an Exception can be re thrown.
1. catch an Exception, and further throw same Exception object(as shown in above example)
2. catch an Exception, and further create a new Exception object, and throw it(as shown in below example)

class MyException extends Exception{
}

class TDemo22{
	public void met2() throws Exception
	{
	try
	{
	String str="2abcd3";

	int i = Integer.parseInt(str);
	}
	catch(Exception ep)
	{
	System.out.println("Exception catching");
	throw new MyException(); //re throwing a new Exception object
	}
	}
}

public class NumberFormatDemo {
	public static void main(String args[])
	{
	try{
	TDemo22 td2 = new TDemo22();
	td2.met2();

	}catch(Exception e)
	{
	e.printStackTrace();
	}
	}
}

When rethrowing an Exception may be required?
1. When you want to partially handle Exception situation, and further let invokers of your method, to handle the Exception.
2. When you want to hide class name of your internal exception, and rethrow another Exception.

You may also like to read:
How to print stack trace to a log file
List of inbuilt exception in Java
What is RuntimeException
How to create your own Exception?

Leave a Reply