`

java - common practice to rethrow exceptions

    博客分类:
  • java
阅读更多

New comer to Java may throw exception in the wrong way, and the net outcome of that is very misleading error message, which can cause the user of the libraries very confused. so it is very vital to keep the exception right. 

 

One common case of dealing message is when you are dealing calls from a lower library and you may guard against potential damage from the down-stream and throw domain specific exceptions. that menas you may need to rethrow exception in cases. 

 

But it is easy to get it wrong. by wrong, it often meaning that the original stack is destroyed on the way to propagate to the final consumer.  Let 's do a comparison on the following code. 

 

Let 's see the code below 

package Syntax.rethrow;

import java.lang.UnsupportedOperationException;
import java.lang.Exception;

public class Rethrow {

	public static void generateException() {
		throw new UnsupportedOperationException();
		
	}
	
	public static void rethrowException() throws Exception{
		try { 
			generateException();
		} catch (Exception ex) {
			// you cannot swallow it 
			throw new Exception("Caught an exception", ex);
		}
	}
	
	public static void rethrowExceptionDestroyOriginalCallstack() { 
		try { 
			generateException();
		} catch (Exception ex) {
			throw ex;
		}
	}
	
	
	public static void main(String[] args) {
		try {
			rethrowException();
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		System.out.println("-=========================");
		try {
			rethrowExceptionDestroyOriginalCallstack();
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}
}

 

and when you run it, you will see error like this.

java.lang.Exception: Caught an exception
	at Syntax.rethrow.Rethrow.rethrowException(Rethrow.java:18)
	at Syntax.rethrow.Rethrow.main(Rethrow.java:33)
Caused by: java.lang.UnsupportedOperationException
	at Syntax.rethrow.Rethrow.generateException(Rethrow.java:9)
	at Syntax.rethrow.Rethrow.rethrowException(Rethrow.java:15)
	... 1 more
-=========================
java.lang.UnsupportedOperationException
	at Syntax.rethrow.Rethrow.generateException(Rethrow.java:9)
	at Syntax.rethrow.Rethrow.rethrowExceptionDestroyOriginalCallstack(Rethrow.java:24)
	at Syntax.rethrow.Rethrow.main(Rethrow.java:39)

 

As you can see, the 

 

throw e;

 may potentially destroy neccessary information. in this case, it is because of the UnsupportedOperationException that cause the program to fail in the first place. 

 

so it is recommended to alwasy to throw with proper inner exception constructed. 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics