Java – should I use throws when using throw?
My method has a return type that throws a NullPointerException
public class Student { public String studentOne() { //code to get name if(name == null) throw new NullPointerException("Error"); else return name; } }
My problem is Should I throw a NullPointerException and a new exception using the public string studentone?
P. S: I know that throwing a NullPointerException is not a best practice But it is necessary in my project
Solution
NullPointerException is an unchecked exception, so you do not need and should not declare it as thrown You do not need to do this for any unchecked exceptions Of course, if you declare them, they will always be ignored by the compiler
As for throwing an NPE, just throw it. If you can't continue this method in case the value is null However, it makes no difference whether it is thrown explicitly or implicitly when it is raised You can only pass custom messages when explicitly thrown
Of course, you can record this behavior in the method, and in some cases it throws NPE to make the user aware of it