I called a method named readFile()
in the main
method, readFile()
throws FileNotFoundException but main
doesn't, like the following:
public static void main(String[] args){
readFile();
}
public static void readFile() throws FileNotFoundException{
Scanner input = new Scanner(new File("file.txt"));
...
}
When I compiled the program, I got an error at readFile()
in the main
method. It seems that I need to throw an exception in the header of main
as well. Why do I need to throw exception in both headers of main
and readFile()
?
Java has some controversy about its exceptions. It has two classes of exceptions. Checked and unchecked. Any exception extending from RuntimeException or Error is unchecked and does not need to be caught or explicitly declared as throwable in a method signature.
FileNotFound is however a checked exception and must either be caught or declared as throwable in the method signature.
The basic idea is that checked exceptions are ones that you may be able to recover from while unchecked exceptions are ones coming from a most likely unrecoverable error in programming.
You can read all about it here: https://docs.oracle.com/javase/tutorial/essential/exceptions/runtime.html
Think of the throws
keyword as a promise; You're saying you're not going to catch the exception now, but you're going to catch it at the calling statement.
The code you currently have in your readFile
method seems perfectly valid, but you need to wrap the calling statement in a try-catch
to appropriately handle the exception.
Your options for handling Exceptions
are to catch them and deal with them immediately or to throw them in the function and propagate the exception up to the caller of the function.
For main
, it makes sense to catch
and handle the exception there.
public static void main(String[] args){
try {
readFile();
} catch (FileNotFoundException e) {
// Do something with `e`
}
}
public static void readFile() throws FileNotFoundException {
Scanner input = new Scanner(new File("file.txt"));
// ...
}
However, you could also do something like this:
public static void main(String[] args){
readFile();
}
public static void readFile() {
try {
Scanner input = new Scanner(new File("file.txt"));
// ...
} catch (FileNotFoundException e) {
// Do something with `e` or handle it accordingly.
}
}
I would advise against throwing exceptions in the main
, but after that it's really a matter of whether you have a "back up" for if something fails. For more information, this question has fantastic detail.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With