views:

501

answers:

4

As a java programmer who wishes to perfect his programming skills, I often come across the situations that I have to create a runtime exception. I know it's a good practice if one use wisely.

Personally, NullPointerException and IllegalStateException are the most commonly used in the softwares that I have created. How about you?

What runtime exceptions do you often use? In what situations do you use them?

+12  A: 

I never throw NullPointerException. For me, it is one that appears naturally in the code when something goes wrong, and that require a developper to look what happens. Then he fixes the cause, and it doesn't happen again.

I use IllegalStateException to signal that an object is incorrectly configured, or that calls are in incorrect order. However, we all know that ideally, an object should ensure it can't be in a bad state, and that you can't call it in incorrect order (make a builder and a resulting object ...).

I use a lot of IllegalArgumentException, when a method detects that it's parameters are not correct. This is the responsibility of any public method, to stop processing (to avoid indirect errors that are more difficult to understand). Also, a few ifs in the beginning of a method serve a documentation purpose (documentation that never diverge from the code, because it is the code :-) ).

     public void myMethod(String message, Long id) {
       if (message == null) {
          throw new IllegalArgumentException("myMethod's message can't be null");
          // The message doesn't log the argument because we know its value, it is null.
       }
       if (id == null) {
          throw new IllegalArgumentException("myMethod's id can't be null");
          // This case is separated from the previous one for two reasons :
          // 1. to output a precise message
          // 2. to document clearly in the code the requirements
       }
       if (message.length()<12) {
          throw new IllegalArgumentException("myMethod's message is too small, was '" + message + "'");
          // here, we need to output the message itself, 
          // because it is a useful debug information.
       }
     }

I also use specific Runtime Exceptions to signal higher level exceptional conditions.

For example, if a module of my application couldn't start, I might have a ModuleNotOperationalException thrown (ideally by a generic code like an interceptor, otherwise by a specific code) when another module calls it. After that architectural decision, each module has to deal with this exception on operations that call other modules...

KLE
Great points man!!
Winston Chen
Great list; I'd add UnsupportedOperationException, which I use all the time with specific implementations of collection interfaces.
Carl
Great answer. I'll pay more attention to the IllegalStateException in the future!
reef
Great answer. I can only +1 once, but I'd do it twice: once for the good explanation, and once for the self-documenting precondition enforcement. I often use assert for those, but illegal argument is an exact fit for the situation.
CPerkins
+2  A: 

I use 'IllegalArgumentException' quite often (relative to other kind of exception). Most of the time, I will try to return default value as soon as it is logical but some of the time it was not. So I use this one.

Another one I use is 'ArrayOutOfBound' (not sure spelling).

:D

NawaMan
+4  A: 

I've always considered that runtime exceptions should represent programming errors (e.g. null reference passed in when not expected, array index out of bounds, etc.) while checked exceptions should represent exceptional conditions in the environment that cannot be "coded away" (e.g. IOException, SQLException).

One violation of this is that sometimes you'll need to wrap what ought to be a checked exception in a RuntimeException, in order to satisfy the definition of an interface. As a brief example, you might have some snazzy implementation of java.util.List that manages a distributed list between multiple machines. Clearly this would throw checked exceptions (probably some subclass of IOException) if defined on its own, but the benefits of making this class implement List is that clients can use it almost transparently, anywhere they use another list.

This can lead to what Joel terms a leaky abstraction, though, so it's important that your documentation is clear what exceptions can be thrown and what they mean! In this case I find a custom subclass of RuntimeException to generally be clearer at communicating the root cause rather than trying to shoehorn it into an existing runtime exception class.

Andrzej Doyle
You are in line with the original thinking for Java, concerning CheckedExceptions. Actually, this is known as the only original feature of Java (all others were taken from successful other languages). But there has been a lot of debate over this, and I feel the current trend is to consider the distinction as a mistake in Java. The exact problems would be off-topic here, you can google them...
KLE
A: 

UnknownException, very usefull :P

i also like org.apache.commons.lang.NotImplementedException

01
I use `throw new UnsupportedOperationException("Not yet implemented");` for parts of my app that are not yet implemented.
Jesper