"Handle or declare. That's the law." - Head First
But, is it a good law? Let me give an example first:
public static void main(String[] args) throws Exception {
m1();
}
static void m1() throws Exception{
m2();
}
static void m2() throws Exception {
throw new Exception();
}
m2()
throws exception and m1()
calls m2()
, meaning it must either handle or declare it. Hmmm let's declare it. Then main()
calls m1()
and it has same poll: declare or handle. I again decided to declare it and code compiles just fine.
Okay, it works, but who handled this exception at all? Looks like no one did. I know I am a beginner, but I don't like the sound of that. Yes, some methods can decide whether to declare or handle exceptions, but why main()
? Shouldn't main method be one that just handles? In that way, no exception could "slip".
Am I missing something to this? I was honestly surprised that it is okay for main method to just declare exception, knowing that it is the last place we could technically catch something.
main
itself, but you can just leave it to the default exception handler. – Hallucinationnot
throw an exception if the wrong password was provided... it was able to validate the user in that case, namely that the login failed. However, if the user database is unavailable, then itshould
throw an exception. – Blackballmain
method must comply with the Java specification. For handled exceptions, a method must contain a try/catch to handle exceptional cases OR it must declare that it can throw someException
. The main method is not exempt from this rule. If this rule is violated, the code simply will not compile. – Capsize