java - common practice to rethrow exceptions

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. 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值