Could NullPointerException cause some problems
I noticed that using the exception "NullPointerException" could cause problems. But I do not understand why? For example in this line of code:
Code:
if (value == null) throw new NullPointerException("The added value is zero.");
What can it happens? The virtual machine can run?
If I replace NullPointerException by IllegalArgumentException is that this will be better? I was told to replace IllegalArgumentException what difference does it gonna happen?
Re: Could NullPointerException cause some problems
Hello,
no, there is virtually no difference between these two exceptions. NullPointerException is traditionally thrown when one tries to use a field or method of a null reference. I therefore tend to advise using IllegalArgumentException, but hey, there is very little difference.
Re: Could NullPointerException cause some problems
I use a plugin in eclipse "PMD" who corrects my code, and when I weighed exception NullPointerException. I put
Avoid throwing a NullPointerException - it's confusing because most people will assume that the virtual machine threw it. Consider using an IllegalArgumentException instead, this will be clearly seen as a program-initiated exception.
I still see no reason why it is preferable to remove as exception IllegalArgumentException instead of NullPointerException?
Re: Could NullPointerException cause some problems
The answer seems clear to me:
- A NullPointerException is a technical error, which usually rise when the case (here: add a null value) is not supported. It is a purely technical mistake
- You want to handle this case, so we advise you to use an IllegalArgumentException for your error message that is already more "functional" (versus technical)
Specifically, we agree that it is the same, it's just a "best practice", you make what you want.
Re: Could NullPointerException cause some problems
Take the example of your item value if you do that then that value is null:
Code:
if ( value. equals ( "" ) ) return ;
your program execution will start automatically NullPointerException to warn that you can not call the equals method on your component value.
Putting
Code:
if (value == null) throw new NullPointerException ("The value added is zero.") ;
has returned the same exception as above but is managed by yourself. PMD advice here is to differentiate an exception that you throw yourself directly because the argument is incorrect with an exception launched by the JVM directly. The purpose is the same (well, depending on the catch of your application) but will in fact seeing someone logs easier to understand the type of problem and especially to understand that you manage the exception and that it is not the JVM that it launches
In writing this:
Code:
if ( value == null ) throw new IllegalArgumentException ( "The value added is zero." ) ;
If the exception is thrown, the logs will be readable as a problem on a method argument (not an unhandled exception in your application)