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)
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.
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.
Some common unchecked exceptions in Java are NullPointerException, ArrayIndexOutOfBoundsException and IllegalArgumentException.
How to throw an exception? Here, the throwkeyword is used to throw a new exception object if the passed-in parameter has invalid value.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With