2

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.

Community
  • 1
  • 1
drifter
  • 683
  • 1
  • 11
  • 24
  • Are you trying to do some action based on the exception type? I mean different exception type for different invalid input? – yadab Feb 05 '12 at 21:03

1 Answers1

6

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.

Adam Zalcman
  • 26,643
  • 4
  • 71
  • 92
  • CustomIllegalArgumentException is to combine NUllPointerException and IllegalArgumentException that can be thrown in my methods to have clear Log. – drifter Feb 05 '12 at 20:33
  • 1
    Generally, I prefer to have more detailed error _messages_ rather than trying to whip up my own exception _type_. – Louis Wasserman Feb 05 '12 at 20:35