What is the best way to catch an IllegalArgumentException

When is it best to use this type of exception and is it handled correctly if it is caught in such a catch?

catch(Exception e) 

Or should it be clearly caught?

 catch(IllegalArgumentException e) 
+7
java exception
source share
4 answers

That would have been caught first, but there would have been many other exceptions. You should not catch more than you really want.

The second is better if you really need to catch it ... but usually this indicates an error in the calling code. Sometimes this is the case of another method, above which its arguments are not checked, etc. In an ideal world, anytime an IllegalArgumentException thrown, there must be a way so that the caller can check the value before passing it or call the version that fails in a non-standard way (for example, the TryParse pattern in .NET, which is admittedly more complicated in Java without out parameters). This is not always the case, but whenever you get an IllegalArgumentException , it is worth checking if this can be avoided by checking the values ​​before calling the method.

+12
source share

You should not handle an IllegalArgumentException. He must tell the developer that he called the method with the wrong arguments. The solution is to invoke the method with other arguments.

If you must catch him, you must use

 catch(IllegalArgumentException e) 
+7
source share

You should stay away from catch (Exception) , as you will understand all possible exceptions. If you really expect an IllegalArgumentException and handle this case, you should not expand this scope; it is better to add additional catch blocks for other types of exceptions.

+3
source share

It really depends on the existing business, or in itself is correct. Without narrowing down the scope of questions, it’s a little difficult to give an example of β€œbetter use”.

0
source share

All Articles