Reputation: 683
Does it good idea to have custom exception like IllegalArgumentException and throw it in all cases when methods can get null reference instead of valid object value?
public void method(String str){
if(str == null)throw new CustomIllegalArgumentException("str cannot be null");
}
I think that such way I can always see difference between such illegal argument exceptions and other RuntimeExceptions.
Does it good idea or not?
P.S.: I looked at such posts like Avoiding != null statements
**UPDATE:**So I will know that is programmer-intended exception and I will have clear log.
Upvotes: 2
Views: 2939
Reputation: 27233
IllegalArgumentException
is a standard, not a custom exception. It is conventional to throw NullPointerException
when argument is null
when it shouldn't be.
You should in general prefer standard exceptions when they are suitable to your special case. See also item 60 in "Effective Java 2nd edition" ("Favor the use of standard exceptions"). One advantage of this is that you can write a single handler for similar conditions which may occur both in your own code and in libraries you use.
In order to differentiate the exceptions, you should use the string message they carry. Also, the stack trace will indicate whether the exception has been thrown from your own code or from other code. No need for extra exception class.
One case when it may be reasonable to create your own exception class is when you need the exception to carry extra information about the exceptional condition it indicates. In this case you should still derive the exception from the appropriate standard class, so that a single handler can be written that handles exceptions for similar conditions coming from both your own code and libraries you use.
See also Preconditons
utility class from google. In particular checkNotNull()
utility method which also throws NullPointerException
when its argument is null
.
Upvotes: 6