I have a very simple question about re-throwing exception in Java.
Here is the code snippet:
public static void main(String[] args) throws FileNotFou
Both versions will output the same stacktrace
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 output
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;
}
}
}
will output exactly the same 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)
An advisable approach is to throw your own exceptions. wrap the exception you just caught into it if you want to provide details of the root cause (might be 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 issue (my process did not complete), and the root cause that led to it (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)