tags:

views:

85

answers:

4

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)
A: 

It really depends on the case at hand, either is correct in itself. Without narrowing down the scope of the question, it's a bit hard to give a "best use" example.

cjstehno
+3  A: 

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.

Joey
+1  A: 

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.

Jon Skeet
+3  A: 

You should not handle an IllegalArgumentException. It's porpose is to inform the developer, that he have called a method with wrong arguments. Solution is, to call the method with other arguments.

If you must catch it you should use

catch(IllegalArgumentException e)
Arne