【发布时间】:2016-10-14 17:53:13
【问题描述】:
我试图捕获一个特定的异常并处理它,然后抛出一个通用异常,该异常执行代码来处理任何异常。这是如何实现的?这个 sn-p 没有捕捉到 Exception 所以输出是
Exception in thread "main" java.lang.Exception
at Main.main(Main.java:10)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)
IOException specific handling
Process finished with exit code 1
sn-p:
import java.io.IOException;
public class Main {
public static void main(String[] args) throws Exception {
try {
throw new IOException();
} catch (IOException re) {
System.out.println("IOException specific handling");
throw new Exception();
} catch (Exception e) {
System.out.println("Generic handling for IOException and all other exceptions");
}
}
}
【问题讨论】:
-
这在什么方面失败了?您到达了
catch块,因为消息"IOException specific handling"已打印。然后应用程序以异常退出,因为您抛出了异常。 -
@David 我希望执行 Exception 块中的代码。
-
@newToScala 在第一条评论中查看我的链接问题,它解释了为什么/如何您的代码完全按照它应该的方式执行。
-
@newToScala:
IOException块优先,因为抛出了IOException。只使用了一个catch块。如果你想捕捉你正在抛出的Exception,你需要将整个操作包装在一个 try/catch 中。
标签: java