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.
本文探讨了在Java编程中正确处理异常的重要性,特别是如何避免在异常传播过程中破坏必要的信息。通过对比不同的异常处理方法,本文揭示了不当处理可能导致的问题,并强调了构建合适的内部异常构造来保持原始调用堆栈完整性的必要性。
1425

被折叠的 条评论
为什么被折叠?



