Reputation: 541
public static void main(String[] args) throws IllegalArgumentException {
if (args[0].matches(".*\\w.*")) {
throw new IllegalArgumentException("Can't input characters!");
}
String input = insertSpaces(args[0]);
args = input.split("\\s+");
printAnswer(calculate(args),args);
}
In the above code, the main method throws an IllegalArgumentException. How do I catch the exception thrown from the main method? The reason I ask, and if I'm incorrect please correct me, is because my understanding is that when a method throws an exception, the caller of the method is responsible for catching the exception. The main method in this case has no other method calling it so I can't figure out how to catch the exception. I'm guessing the JVM is working behind the scenes to call the method but then how would I make the JVM catch the execption. Please provide CODE if possible along with explanation. Otherwise explain why not possible.
Upvotes: 1
Views: 2047
Reputation: 3433
Don't ever throw an exception from the main
method.
Don't ever let the main
method crash from an exception.
IllegalArgumentException
, like any runtime exception, is a result of the programmer messing up. Fix what you messed up.
Don't catch it, prevent it.
Upvotes: 0
Reputation: 2790
Best practice is avoiding them on main
method call and handle it and show user a meaningful message about what happened and decide continue or terminate.
As Joe C mentioned you can let it throw so JVM will handle and the user or caller will see the stack trace. When you make such a decision (using throws on main) it is the moment that you can do nothing about exception. i.e. you receive required file name as arg but file is not there. If you don`t do logging to external resources probably you want to let JVM print stacktrace
Upvotes: 1