我可以在java中实现链式异常工具
案例1:
public static void main(String[] args) {
try {
method1();
} catch (Exception e) {
System.out.println("Exception in the main method :: "+e);
}
}
private static void method1() throws Exception {
try{
System.out.println("Inside Try Block"+10/0);
} catch(ArithmeticException e){
System.out.println("Exception in method1 :: "+e);
throw e;
} finally{
System.out.println("In FinallY Block");
}
}
案例2:
public static void main(String[] args) {
try {
method1();
} catch (Exception e) {
System.out.println("Exception in the main method :: "+e);
}
}
private static void method1() throws Exception {
try{
System.out.println("Inside Try Block"+10/0);
} catch(ArithmeticException e){
System.out.println("Exception in method1 :: "+e);
throw (ArithmeticException)new ArithmeticException().initCause(e);
} finally{
System.out.println("In FinallY Block");
}
}
我得到的输出为
Exception in method1 :: java.lang.ArithmeticException: / by zero
In FinallY Block
Exception in the main method :: java.lang.ArithmeticException: / by zero
我的问题是:
- 这两种情况有什么区别吗?
- 哪种方法更好?
- 为什么有 2 个案例具有相同的目的?
最佳答案
不同之处在于,在第二种情况下,您将原始
ArithmeticException
异常包装在另一个相同类型的异常中(请参阅下文,了解为什么这是毫无意义的)。情况 1 可能是您想要在此处使用的情况,因为您没有扩大异常的含义(到更高的级别)。
他们没有相同的目的,让我解释一下......
如果将异常设置为原因,则其含义不同。您可以通过将 ArithmeticException 包装在更高级别的异常中来赋予它更大的含义。在这里,您只是将其包装在另一个 ArithmeticException
中,这是没有意义的。
您可能需要一个原因的情况是,例如,当您尝试从 Web 服务获取一些数据时:发送 HTTP 请求的低级方法抛出一些 SocketException
或 HttpException
,然后将它们包装在一些更高级别的异常中,描述无法加载的资源(例如)。
关于java - JAVA 中的链式异常设施,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22510851/