两个版本都将输出相同的堆栈跟踪
没有尝试/捕获
import java.io.FileNotFoundException;
import java.io.FileReader;
public class Test {
public static void main(String[] args) throws FileNotFoundException {
// try {
FileReader reader = new FileReader("java.pdf");
// } catch (FileNotFoundException ex) {
// throw ex;
// }
}
}
将输出
Exception in thread "main" java.io.FileNotFoundException: java.pdf (The system cannot find the file specified)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(FileInputStream.java:195)
at java.io.FileInputStream.<init>(FileInputStream.java:138)
at java.io.FileInputStream.<init>(FileInputStream.java:93)
at java.io.FileReader.<init>(FileReader.java:58)
at Test.main(Test.java:7)
尝试/捕获/抛出相同的异常
import java.io.FileNotFoundException;
import java.io.FileReader;
public class Test {
public static void main(String[] args) throws FileNotFoundException {
try {
FileReader reader = new FileReader("java.pdf");
} catch (FileNotFoundException ex) {
throw ex;
}
}
}
将输出与以前完全相同
Exception in thread "main" java.io.FileNotFoundException: java.pdf (The system cannot find the file specified)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(FileInputStream.java:195)
at java.io.FileInputStream.<init>(FileInputStream.java:138)
at java.io.FileInputStream.<init>(FileInputStream.java:93)
at java.io.FileReader.<init>(FileReader.java:58)
at Test.main(Test.java:7)
尝试/捕获/抛出包装异常
一个可取的方法是抛出你自己的异常。如果您想提供根本原因的详细信息(可能需要或不需要),请将刚刚捕获的异常包装到其中
import java.io.FileNotFoundException;
import java.io.FileReader;
public class Test {
public static void main(String[] args) {
try {
FileReader reader = new FileReader("java.pdf");
} catch (FileNotFoundException ex) {
throw new RuntimeException("Error while doing my process", ex);
}
}
}
您可以清楚地看到顶层问题(我的过程没有完成),以及导致它的根本原因(找不到 java.pdf 文件)
Exception in thread "main" java.lang.RuntimeException: Error while doing my process
at Test.main(Test.java:9)
Caused by: java.io.FileNotFoundException: java.pdf (The system cannot find the file specified)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(FileInputStream.java:195)
at java.io.FileInputStream.<init>(FileInputStream.java:138)
at java.io.FileInputStream.<init>(FileInputStream.java:93)
at java.io.FileReader.<init>(FileReader.java:58)
at Test.main(Test.java:7)