Both versions will produce the same stacktrace file
without try / catch
import java.io.FileNotFoundException; import java.io.FileReader; public class Test { public static void main(String[] args) throws FileNotFoundException {
displays
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)
with try / catch / throw with the same exception
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; } } }
will be displayed exactly as before
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 wrap exception
The recommended approach is to throw your own exceptions. complete the exception that you just got into it if you want to provide information about the root cause (maybe wanted or not wanted)
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); } } }
You can clearly see the top-level problem (my process is not completed), and the main reason that led to this (java.pdf file not found)
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)
Julien
source share