The intent of both exceptions is quiet different
NPE
- in most scenarios that I can think of it occurs due to programming errors, so should not be handled.
In case of null
, NPE
should be thrown in a fail fast manner as it affects the trace. For which I personally use Preconditions.checkNotNull(E ref, String message)
of Guava.
IAE
- This means there that the class did not expect such a value from the caller. There can be scenarios when you can catch that exception and use default value for recovering.
I know that with both being RuntimeExceptions they hardly ever get
caught
According to me this is quite a misconception that Runtime exceptions are hardly ever caught. Nowadays APIs are depending more on Runtime exceptions as they want to leave on the caller to decide whether the exception gets caught. Many APIs impose you to catch many exceptions which leads to a lot of pain when you know that exception is never going to occur. You are forced to catch it and leave an empty catch block or better log that it should not occur.
The APIs do however specifically document when a particular exception is meant to occur.
Take an example of Integer.parseInt(String s)
which throws NumberFormatException
and which is a Runtime exception, in most scenarios when I have used it I always catch it and do some recovery using default values.
Think of the scenario if NumberFormatException
would have been a checked exception, and you making a call Integer.parseInt("1")
, it is clearly visible that it won't occur but still you will be forced to catch it. Agreed that the example is a hypothetical one, but gets my point through.
Again this is just my opinion based on my experience.
I'm asking if they ever get handled differently.
As I have wrote NPE is not caught in most scenarios, but there are always exceptions. Like suppose there is a part of your system that is kept open for extension for someone else to program and there is NPE in that code and you don't want the upper layers to be affected by it then I catch NPE and remove that component from the system giving proper logs and traces. A concrete example is a pluggable system, I didn't want my whole system to crash due to programming error in a user written plugin. So I caught Exception
. This may be a bad example for others but worked for me.