throw Keyword in Java

In java, throw keyword is used to throw an exception explicitly. Using “throw keyword” we can throw checked, unchecked  exceptions and user -defined exceptions.

The throw keyword is mainly used to throw the custom exception. We will discuss these in tutorial User defined exceptions. The only object of the Throwable class or its sub-classes can be thrown. Program execution stops on encountering throw statement, and the closest catch statement is checked for a matching type of exception.

Now let’s understand the uses of throw keyword with an easy example.

 

Create instance of Throwable class –

There are two possible ways to get an instance of class Throwable.

  • Using a parameter in a catch block.
  • Creating instance with new operator.

    new NullPointerException(“test”);

  • This constructs an instance of NullPointerException with name test.

The output of the above code will be – Exception caught java.lang.ArithmeticException: Throw exception explicitly

 

Selenium Testing Video Tutorial:

 

In the above example the Test() method throw an instance of ArithmeticException, which is successfully handled using the catch statement.

So using this throw keyword is used to throw the checked, Uncheck and user defined exception explicitly.

 

0 Comment

Leave a Reply