Vikram
Vikram

Reputation: 2072

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

Upvotes: 3

Views: 117

Answers (2)

Ilya
Ilya

Reputation: 29693

Better solution is to add documentation to method

/**
 * @param  name - not null. NullPointerExcpetion will thrown in case of null
 *
 * @return some string
 */  
public String studentOne(String name)
{
   // ...
}      

There is no difference between

 public String studentOne(String name)  

and

 public String studentOne(String name) throw NullPointerException

because NullPointerException is unchecked exception

Upvotes: 1

Rohit Jain
Rohit Jain

Reputation: 213281

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.

Upvotes: 6

Related Questions