Tuesday, 16 May 2017

Difference between throw and throws in Java

Throw:

* Throw is a keyword in java.
* Used to throw an exception.
* Throw is followed by an instance of the class.
* Throw is used within the method.
* You can throw a single exception at a time.

Example:
public void M(){
    throw new NullPointerException();
}


Throws:
* Throws is a keyword in java.
* Used to declare the exception.
* Throws is followed by class.
*Throws used with method signature.
* You can declare multiple exceptions.

Example:
public void M() throws IOException{
throw new IOException();
}

No comments: