Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I use throws while using throw?

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

like image 263
Vikram Avatar asked Jul 13 '26 01:07

Vikram


1 Answers

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.

like image 70
Rohit Jain Avatar answered Jul 15 '26 14:07

Rohit Jain