Reputation: 91
I wanted to specifically ask this question. Why should I put
public static void main(String[] args) throws Exception { ... }
instead of simply
public static void main(String[] args) { ... }
at the top of the program. I am always wary of throwing a general Exception. I just want to understand the purpose of throwing an Exception on the main method.
Upvotes: 0
Views: 1923
Reputation: 455
It delegates checked exceptions to the JVM, which will catch the exception in its default exception handler. The default exception handler will then print the exception's stack trace and terminates the main thread.
Upvotes: 0
Reputation: 73
Here is the breakdown.
public static void main(String[] args) throws Exception { ... }
All this does is document that the method potentially throws this exception and you are clearly stating that you are NOT catching this exception. So it tells others that are going to use this method that they need to encapsulate this call within a try/catch of their own, or handle it otherwise.
So in your case, it doesn't make sense to indicate that your main method throws anything, since that's the starting point of the application, and well if there is an exception, then your application will not run.
Upvotes: 2
Reputation: 833
I can think of no good reason to throw Exception
from a main method. This seems like a code smell to avoid handling checked exceptions throughout the program.
Upvotes: 0
Reputation: 1375
This is a good place to start: https://docs.oracle.com/javase/tutorial/essential/exceptions/
Exceptions are there to let the program exit "gracefully". So for example if your program had a line to read files, your program can have FileNotFoundException
which would allow for it to not crash but rather throw an exception. You can even output your own comments to give hints as to why the exception was thrown.
Upvotes: 0