Question:
A situation has arisen in which I get data from the Intent
, it is necessary to process it for a NullPointerException, but if it suddenly throws this Exception, then you still need to crash the program, because this behavior is unacceptable, but to add a comment why it happened this way, I, in turn, do this
try{
mCPath = new CPath(intent.getStringExtra(EXTRA_CPATH));
}catch(NullPointerException e){
throw new NullPointerException("EXTRA_CPATH must be not null");
}
But my team lead says that it's not so good, you need to throw another exception, namely RuntimeException
try{
mCPath = new CPath(intent.getStringExtra(EXTRA_CPATH));
}catch(NullPointerException e){
throw new RuntimeException("EXTRA_CPATH must be not null");
}
I do not quite understand the logic, in this context of the program, in my personal opinion, if you receive Null, then you need to throw null, just add a comment or am I wrong?
Answer:
(Extrapolating information from .NET, I could be wrong.)
NullPointerException
is a system exception that is thrown in the bowels of the Java virtual machine, which occurs when accessing a near-zero address, which is generally monitored at the operating system level. Bad form – and catching an exception, and throwing it.
You don't need to catch the exception, because accessing a null object is an error in the application logic. If some variable or some field is null, then you need to check this value, and not rely on the fact that the runtime will throw NPE.
You don't need to throw an exception, because programmers can expect the exception to be thrown at the system level rather than manually generated by custom code.
What is the right thing to do in your case? Check intent
for null, and if the value is absent, then throw the most logical exception, and at least IllegalStateException
. If null was supplied as an argument, then an IllegalArgumentException
should be thrown. And there certainly shouldn't be any try-catch.
It looks like Java has different views on using exception, but overall my point of view prevails. See also:
- Is it okay to throw NullPointerException programatically?
- IllegalArgumentException or NullPointerException for a null parameter?