Home » java » Throw Keyword in Java

Throw Keyword in Java

In java programming, If the exception occurs within try block it is thrown.

A system generate exception is automatically thrown by java run time system but if we want to  manually thrown an exception, we can do so by using throw keyword. 

Syntax: 

           throw    ThrowableInstance;

here, ThrowableInstance must be an object of type Throwable or subclass of Throwable.

Example: write a program to demonstrate throw keyword.

Note:  In this program new is used to create an instance of NullPointerException and we get two chance to deal with the same error.

In the line  “throw new NullPointerException(“demo”);” 

throw keyword is used to throw  NullPointerException(“demo”). Here we set “demo” is a name of exception.

This NullPointerException(“demo”) catch by catch() method which resides in a demo() method.

 Line “throw e;”  re-throw the exception which is catch by catch() method which resides in a main() method.

            

Please follow and like us:
error