No, my opinions as expressed in this blog are not those of my employer. They're mine alone. That's why they're called "my opinions." Helloooo.

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.

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).

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.

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!

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.

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?

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)

"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:

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!

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.

This is a smart blog. I mean it. You have so much knowledge about this issue, and so much passion. You also know how to make people rally behind it, obviously from the responses. Youve got a design here thats not too flashy, but makes a statement as big as what youre saying. Great job, indeed. Acuvue Advance Astigmatism

Compared with traditional today's watches, these collectible watches may not be water protected. Prevent him or her from entering water and humidity to cease oxidation. Heat at the same time plays replica louis vuitton handbags a vital role indoors routine care. Classic Replica Watches UK timepieces like the require watching room fake Audemars Piguet watches temperature to guarantee they carry on longer all the way through operate together with in bonus. In case it does not matter the reason a specific thing bad replica Rado goes on, do possibly not worry. You may see pros what person conduct restoration and likewise refurbishment, automotive best IWC replica watches crash transpires, or could be if this wrist watch stops working as a consequence of age. Having a majority of these watches for outdated will have to have lots for care, if everyone count only on their worth to learn, or you ought to maintain any skill and likewise history of them watches.