Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to catch an IllegalArgumentException

Tags:

java

exception

When would be the best use of this type of exception and is it handeled properly if caught in a catch like so?

catch(Exception e)

Or does it need to be caught explicitly?

catch(IllegalArgumentException e)
like image 412
ChadNC Avatar asked Jan 22 '10 13:01

ChadNC


People also ask

How do you catch IllegalArgumentException?

To catch the IllegalArgumentException , try-catch blocks can be used. Certain situations can be handled using a try-catch block such as asking for user input again instead of stopping execution when an illegal argument is encountered.

When should you throw IllegalStateException?

The IllegalStateException is thrown when the Java environment or application is not in an appropriate state for the requested operation. This can occur when dealing with threads or the Collections framework of the java. util package under specific conditions.

Is IllegalArgumentException a checked exception?

Some common unchecked exceptions in Java are NullPointerException, ArrayIndexOutOfBoundsException and IllegalArgumentException.

How do you throw an invalid exception in Java?

How to throw an exception? Here, the throwkeyword is used to throw a new exception object if the passed-in parameter has invalid value.


2 Answers

You should stay away from catch (Exception) since that way you'll catch every possible exception. If you really only expect the IllegalArgumentException and handle that case you shouldn't broaden that scope; better add more catch blocks for other types of exceptions, then.

like image 147
Joey Avatar answered Nov 15 '22 21:11

Joey


It would be caught by the first - but so would a bunch of other exceptions. You shouldn't catch more than you really want to.

The second is better if you really have to catch it... but usually this indicates a bug in the calling code. Sometimes this is a case of another method higher up not validating its arguments, etc. In an ideal world, any time that IllegalArgumentException is thrown there should be a way for the caller to validate the value before passing it in, or call a version which will fail in a non-exceptional way (e.g. the TryParse pattern in .NET, which is admittedly harder in Java without out parameters). That's not always the case, but whenever you get an IllegalArgumentException it's worth checking to see whether you could avoid it by checking the values before calling the method.

like image 44
Jon Skeet Avatar answered Nov 15 '22 20:11

Jon Skeet