Java – Throw

Java – Throw 2017-08-09T13:29:18+00:00

Java Throw :

We saw that an exception was generated by the JVM when certain run-time problems occurred.

It is also possible for our program to explicitly generate an exception.

This can be done with a throw statement. Its form is as follows:

Throw object;

Inside a catch block, you can throw the same exception object that was provided as an argument.

This can be done with the following syntax:

catch(ExceptionType object)

{

throw object;

}

Alternatively, you may create and throw a new exception object as follows:

Throw new ExceptionType(args);

Here, exceptionType is the type of the exception object and args is the optional argument list for its constructor.

When a throw statement is encountered, a search for a matching catch block begins and if found it is executed.

EX :

 


Output :
Before a
Before b
We r in b
********
c : java.lang.ArithmeticException: / by zero
J : java.lang.ArrayIndexOutOfBoundsException: demo
********
After a
Throwing our own object :
?If we want to throw our own exception, we can do this by using the keyword throw as follow.
throw new Throwable_subclass; 
Example : throw new ArithmaticException( );

throw new NumberFormatException( );

EX :

 


Output :
Caught MyException
Number is too small
java2all.com
Here The object e which contains the error message “Number is too small” is caught by the catch block which then displays the message using getMessage( ) method.
NOTE: 
Exception is a subclass of Throwable and therefore MyException is a subclass of Throwable class. An object of a class that extends Throwable can be thrown and caught.

Prev Next