Re: IllegalArgumentException vs. NullPointerException and collection behavior



Karsten Wutzke wrote On 08/10/07 10:47,:
When passing nulls to my methods and constructors (for required
fields), is it better to use IllegalArgumentException("Blah is null!")
or NullPointerException("Blah is null!")?

Eric Sosman wrote:
There's no hard-and-fast rule, but it seems to me more
straightforward to throw IllegalArgumentException (or one
of its subclasses) when an argument fails a validity check.
Sometimes, though, I will let Java do the validity checking
for me, as in

void method(String bass) {
String lower = bass.toLowerCase();

This idiom has the disadvantage that you do not control logging the error.

TABs in a Usenet post are a Bad Thing.

.... instead of

void method(String bass) {
if (bass == null)
{ // good practice: always use braces in your ifs, etc.
String msg = "suitable error message";
logger.error( msg );
throw new IllegalArgumentException(
msg
);
}
String lower = bass.toLowerCase();

.... in which case the caller will get NPE instead of IAE.
Whatever you do, make sure the Javadoc explains all the
requirements you impose on the argument values: non-nullity,
no zero-length strings, all alphabetic, whatever.

Like so much of programming, Java gives you the tools but no restriction on which to use; it is a judgment call. There is an advantage to declaring a checked exception - it forces client programmers to pay attention to it. The trouble with throwing any RuntimeException is that the API clients might fail abruptly because their programmers didn't pay close enough attention to the Javadocs.

Fail without throwing any exception when it makes sense to return a value within the range of the method. For example, a database lookup for a name might reasonably return null for a database failure as well as for the name not being there; from the application standpoint it might not matter why the name couldn't be found. The lookup method should log the db error and return null.

Fail with an exception when it makes sense that the failure condition is "out of band" for the method. In the preceding example, if the database failure meant that the rest of the application would have trouble (e.g., an insert is next), it would be better to throw the exception so the application doesn't try something already known to be doomed to fail.

Use a RuntimeException if the situation is sufficiently under the client's control that they shouldn't have let it happen. Throw a checked Exception if the client should have been able to count on getting a result, and you want to force awareness of any out-of-band problems. So an IllegalArgumentException (or NPE) is appropriate when the client passed a null value, but shouldn't have, whereas a checked FooException is a better choice when the client is accessing a resource that becomes unavailable for extrinsic reasons.

Do not use assertions for run-time data checks. Assertions are to check program invariants that are under your control (e.g., preconditions for private methods).

Designing wisely is the goal; mastery comes from not ever assuming one has mastered it.

--
Lew
.



Relevant Pages

  • Re: Client Firewall and Outlook
    ... Additionally there are times when a user is on the phone to a client, ... I am trying to add Outlook ... as an exception to the firewall list. ... on windows firewall in control panel. ...
    (microsoft.public.windows.server.sbs)
  • Re: Code design ideas?
    ... app and the webservice, etc. ... Errors of type 1 should be handled by the client side. ... Usually it is the Message of the Exception. ... severity levels: warning and error. ...
    (microsoft.public.dotnet.languages.csharp)
  • friendly error messages for usernameForCertificateSecurity
    ... returned to the client in a simple way. ... In the code above if I comment out the throwing of the soap exception on the ... "Security requirements are not satisfied because the security header is not ... true error message is a less then desireable solution. ...
    (microsoft.public.dotnet.framework.webservices.enhancements)
  • Re: Benefits of Dynamic Typing
    ... The latter problem is detected in parts not specific to the compiler, ... and the only information about the reason is carried by the exception ... the entire Map call fails with the same exception. ... but it did expect that some application might fail. ...
    (comp.lang.functional)
  • Assmebly.Load error using Byte()
    ... I have 2 WebApplication project (dummy and dummy2). ... The first is trying to load a UserControl compiled in the second. ... The web sites are formed of a client part and an administration part. ... An unhandled exception occurred during compilation using ...
    (microsoft.public.dotnet.framework.aspnet)