I'm handling for the first time Exceptions in Java and I want to know if this this the good way to go.
public static void main(String[] args) throws FileNotFoundException {
submethod();
}
static void submethod() throws FileNotFoundException {
Scanner scan = new Scanner(new File("file.txt"));
while (scan.hasNextLine()) {
// do somethig...
}
}
The thing that sounds strange to me is the explicit declaration throws FileNotFoundException
also in the main
method, otherwise the compiler reports:
error: unreported exception FileNotFoundException; must be caught or declared to be thrown
I wanted to know if I'm doing it wrong. In a more complicated project, where you need to catch much more exceptions, it would become very messy. Is this the better practice to handle exceptions? And why do I need to declare it in both methods?
Specifying the
FileNotFoundException
in thethrows
clause is needed becauseFileNotFoundException
is a checked exception. The other option is to catch the exception and handle it using atry-catch
.It is up to your program requirements to decide on how to handle the exception. For example, if you want to print a certain error message when the exception is thrown, you can catch it:
However, in a simple case like the one you have, it would make sense to just terminate the program when the exception occurs. Hence you can just declare the methods to throw the exception as you just did.
In more complex scenarios, you may want to catch the exception, print something to the user, and continue the program. For example, if
submethod
is used only to read a file provided by the user, then you can keep thethrows
as it is. However, the caller of the method may want to handle the exception in case it is thrown, and maybe ask the user to re-input another filename.