My method has a return type that throws NullPointerException.
public class Student {
public String studentOne() {
//code to get name
if(name == null)
throw new NullPointerException("Error");
else
return name;
}
}
my question is .. Should I use public String studentOne throws NullPointerExceptionwhile throwing new exception?
P.S : I know its not bestpractice to throw nullPointerException. But its required in my project
NullPointerException is an unchecked exception, so you don't need to and should not declare it as thrown. You don't need to do this for any unchecked exception. Of course, if you declare them, they would anyways be ignored by the compiler.
As for throwing a NPE, it's just fine to throw it, when you can't proceed in the method in case the value is null. But it wouldn't make any difference whether you throw it explicitly, or it is implicitly thrown when it is raised. Just that you can pass customized message when you explicitly throw it.
Of course, you can document this behaviour in the method, that it will throw a NPE, under certain circumstances, so as to make the users aware about that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With