どちらのバージョンも同じスタックトレースを出力します
トライ/キャッチなし
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)
try/catch/throw と同じ例外を使用
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)
try/catch/throw ラッピング例外
推奨されるアプローチは、独自の例外をスローすることです。根本原因の詳細を提供する場合は、キャッチした例外をラップします (必要な場合とそうでない場合があります)。
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)