Monday, June 16, 2008

Common Java unchecked exception types

I've noticed a lot of confusion about what type of unchecked exception is the right one to throw under various circumstances. Here's a very simple explanation of the most common types.

NullPointerException - multiple schools of thought on this one. Of course, it's thrown automatically by the runtime when you try to dereference null. Many say that you should never rely on this behavior, and should always check for null explicitly. Many also believe that when you find a null reference, you should throw IllegalArgumentException instead of NPE. This way, a thrown NPE always indicates some programming error in the implementation of the method, not a failure of the caller to pass valid parameters. I'm not taking a stand on this issue right now.

IllegalArgumentException - throwing this exception implies that there exists at least one other value for this parameter that would have caused the check in question to pass. If the caller can't remedy this exception by substituting another value for the argument in question, it's the wrong exception to throw. Note that in some of these cases IndexOutOfBoundsException is more appropriate (and strangely, IOOBE doesn't extend IAE).

IllegalStateException - this exception implies that there are no argument values that could have caused the check to succeed, yet, there does exist at least one alternate state that the instance in question could have been in, which would have passed the check. Note that this type almost never makes sense for a static method, unless you rely heavily on static state (shame on you). Note also that this exception is appropriate whether or not it is possible to actually mutate this aspect of the instance's state, or it's already too late.

UnsupportedOperationException - this means that the method invoked will always fail for an instance of this class (concrete type), regardless of how the instance was constructed.

AssertionError - this is the right exception to use whenever a statement should by rights be impossible to reach.

I hope this helps. Any points you want to argue?

15 comments:

Boris Bokowski said...

Thanks, this is almost worth linking to... why are you not taking a stand on the issue whether or not to throw NPEs?

Kevin Bourrillion said...

Only because I wanted to spend only five minutes making this post. :)

leonardinius said...

Hi all,
Sorry for my poor english.

It's more interesting topic I used to think about it.
I feel kinda embarrassed a little, because (sometimes) I've used UnsupportedOperationexception to mark a method which could not perform such as operation;
//pseudocode[[
class SomeService {
void doSomeStuff(OperationCode opcode) throws UnsupportedOperationexception, ServiceException
};
//pseudocode]]

I think I should dig into javadocs alittle bit more. But, at the first moment it seems natural.

For example: we are talking about Integer.parse(String s) or smth.. It assumes we want to process that parameter and get the result. If we are passing "a", so no result could be obtained and we throw IllegalArgumntException, because we can not proceed and it does make sence here - because we are working with well-known ("predefined" ..hmm. bad word) objects( which even could be runtime generated).

But that about some kind of dynamic/runtime construsted/assembl ed operations (as in my example). If we throw IllegalArgumenException - we explicitely say - we do not support this argument. But if throw UnsupportedOperationException - then we explicitely say - we could not perform an operation like that.

So// my 2 cents. I feel like I need to dig into javadocs and read more (what's the intent of these exception?..). I just tried to explain, what was my assumption and stumbling block (me at least).

Buddy Casino said...

And of course, you never throw AssertionError yourself, since its name says that it is an error and not an exception. Therefore, it should only be caused by a failed assert statement, and the JVM will be happy to throw this one on your behalf.

Kevin Bourrillion said...

Buddy: no, I don't agree. If you have a statement that Can't Possibly Be Reached, you can and should "throw new AssertionError()" explicitly.

Jed Wesley-Smith said...

the NullPointer/IllegalArgument exception is long and boring... we eventually standardised on a NullArgumentException (extending IllegalArg) basically because of one dev who flatly refused to use the libraries if they explicitly threw NPE - crazy!

Robert Konigsberg said...

1. First a nit: regarding NPE / IAE, you don't distinguish between throwing an exception when an argument is null versus throwing an exception when an assignment or value returned from a method is null.

2. Regarding AssertionError, I also strongly disagree with the use case. Consider these two statements:

* An exception that can never be thrown will never be thrown.

* An exception that can never be thrown will never be thrown. except when it's thrown.

My point is that people more often than not consider 1 than 2. People also use AssertionError for case statements where the default case results in an AssertionError. Consider this fragment someone might have written when getting a hold of Java 5, possibly because someone insisted they handle default cases:

TimeUnit timeUnit = ...
switch(timeUnit) {
  case SECONDS: ...; break;
  case MILLISECONDS: ...; break;
  case MICROSECONDS: ...; break;
  case NANOSECONDS: ...; break;
  default: throw new AssertionError(...);
}


When testing with the Java 6 VM, the engineer will get a nasty shock when the application (or, admittedly, merely a thread) when timeUnit is one of the expanded set of enumerated types.

Perhaps my use case is manageable enough: don't throw AssertionErrors in switch statements for enums, or even simpler: prepare for expanded lists of enums. Either way, AssertionErrors loom around the corner.

3. The sixth exception type that is common, based on a per-project basis is the domain-specific exception. In some cases throwing NPE means losing useful domain-specific knowledge that can be used for defect analysis.

Buddy Casino said...

Kevin: putting "assert false" in the place that should never be reached should do the job and is more elegant. I might be wrong, but isn't the point of assertions that they can be enabled/disabled upon program launch using command-line flags? I used to think that throwing AssertionError yourself circumvents that, or am I wrong here?

Casper Bang said...

UnsupportedOperationException is often used as a NotYetImplementedException (which many a library defines themselves).

gigitrix said...

Am in a noob in extending the Exception class myself when neccessary to throw stuff? I always use "normal" exceptions as "programmer oversights" and my own custom exceptions for my own stuff, where the situation is "normal" (invalid input, wierd workaround needed, or whatever)

Andrew J. Montalenti said...

Buddy,

You wrote,

"Kevin: putting 'assert false' in the place that should never be reached should do the job and is more elegant. I might be wrong, but isn't the point of assertions that they can be enabled/disabled upon program launch using command-line flags? I used to think that throwing AssertionError yourself circumvents that, or am I wrong here?"

You are not wrong. Putting "throw new AssertionError()" will circumvent the lack of -ea flag. However, it seems like you've answered your own question. And the answer is, "Don't use assert false"

IMHO, assertions are one of the most misused features of Java 1.5. If a line of code cannot be reached according to your assumptions, why would you EVER want to "optimize out" a call to "assert false"? You save *nothing*, and you lose *everything* -- you lose any indication that anything is wrong. For example, consider the following code:

for (item : items) {
result = null;
ret = processItem(item);
switch (ret) {
case 0: result = op1(item);
case 1: result = op2(item);
default:
// only two valid return values; this code should never be reached
assert false;
}
return result;
}

Now, when this code is run in 'production', your assertion will be optimized out, and now, all of a sudden, this method starts returning null instead of failing. The "assert false" is clearly making asserting an assumption whose violation indicates a programmer error -- an inability for the programmer to update this method in light of the addition of a new return value for processItem. Yet, thanks to the fact that assertions get optimized out, this never gets known in the 'production' environment; this method happily chugs along, reporting nothing. And all for what? CPU time savings? Ugh...

Since the code I work on is not performance-critical, I have made it a rule in my development to boycott assertions. Instead, I provide a static class called "AssertThat" where I have static methods for various kinds of assertions, most of which result in AssertionError. For example:

AssertThat.isTrue(someCondition);
AssertThat.isEqual(obj1, obj2);

One of the scariest things I have seen is a new developer who used the assert keyword in Unit Tests. Since the test runner wasn't run with -ea, the unit tests reported success, even though assertions were failing. Argh!

Buddy Casino said...

Andrew,

I mostly agree with your reasoning, and performance was never one of my arguments.

I just looked up the topic in the SCJP study guide again, and basically it says you should

- use assertions during testing and development (that's why I'm surprised that JUnit doesn't enable them by default, good to know)

- don't use it to validate method arguments

- don't use them in a manner that cause side-effects, since they are not guaranteed to run

Throwing AssertionError manually is of course always guaranteed to run and as such is basically ok, but that wasn't my point.

My objection is that Errors (and AssertionError extends Error, not Exception) should never be thrown in non-jvm code. There is lots of code out there that relies on the assumption that it is sufficient to catch 'Exception' in order to handle errors thrown by ordinary Java code.

In your case, I'd use IllegalStateException. Doesn't fit as well as AssertionError, but then you can always roll your own, e.g. UnreachableBlockException or something like that.

nasha said...

Why was there no follow on bankruptcy then? The bailout of AIG FP went to (wow power leveling) hedge funds that bound credit swaps on Lehman failing or others betting on rating (wow power leveling) declines. AIG has drained over 100 billion from the government. Which had to go to (wow power leveling) those who bet on failures and downgrades. Many of whom (power leveling)were hedge funds. I-banks that had offsetting swaps needed the money from the AIG bailout or they would have been caught. Its an (wow powerleveling) insiders game and it takes just a little bit too much time for most people to think (wow gold) through where the AIG 100 billion bailout money went to, hedge funds and players, many of whom hire from the top ranks of DOJ, Fed, Treasury, etc. ZHANG XIAO CHEN

Affordable Luxurious Wedding Dress Blog said...

cheap wedding gowns,
discount bridal gowns,
China wedding dresses,
discount designer wedding dresses,
China wedding online store,
plus size wedding dresses,
cheap informal wedding dresses,
junior bridesmaid dresses,
cheap bridesmaid dresses,
maternity bridesmaid dresses,
discount flower girl gowns,
cheap prom dresses,
party dresses,
evening dresses,
mother of the bride dresses,
special occasion dresses,
cheap quinceanera dresses,
hot red wedding dresses

asdfsadf said...

nike shoes, jordan shoes, nike dunks, nike air force 1, nike shox, nike shoes, nike shox, nike dunks, nike air force 1, nike shox, nike shoes, nike shox oz, nike shox nz, nike shox r3, nike shox r4, nike shox r5, nike shox tl
nike air force 1










nike Air Force 1, nike shoes, Jordan shoes, nike sb dunks, cheap nike Air Force 1, cheap nike shoes, cheap Jordan shoes, cheap nike sb dunks, discount nike Air Force 1, discount nike shoes, discount Jordan shoes, discount nike sb dunks, nike shoes, nike shox, nike dunks, nike air force 1, jordan shoes, nike shoes, nike shox, nike dunks, nike air force 1, jordan shoes












nike shoes, nike shox, jordan shoes, puma shoes, nike dunks, nike air max, nike air force one, timberland boots, ugg boots, nike shoes, nike shox, nike air force 1, nike sb dunks, puma shoes, nike air max, jordan shoes, ugg boot, jordan sneakers, timberland shoes, bape shoes, nike shoes, nike shox, nike dunks, nike air force 1, jordan shoes