Java2all.com  

Throw





Share This Topic -

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 :

 class Throw_Demo
{
	public static void a()
	{
		try
		{
			System.out.println("Before b");
			b();
		}
		catch(ArrayIndexOutOfBoundsException j)	//manually thrown object catched here
		{
			System.out.println("J : " + j)	;
		}
		
	}
	
	public static void b()
	{
		int a=5,b=0;
		try
		{
			System.out.println("We r in b");
			System.out.println("********");
			int x = a/b;
		}
		catch(ArithmeticException e)
		{
			System.out.println("c : " + e);
			throw new ArrayIndexOutOfBoundsException("demo");	//throw from here
		}
	}
	
	public static void main(String args[])
	{
	
		try
		{
			System.out.println("Before a");
			a();
			System.out.println("********");
			System.out.println("After a");
		}
		catch(ArithmeticException e)
		{
			System.out.println("Main Program : " + e);
		}
	}
}

 
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 :

 import java.lang.Exception;

class MyException extends Exception
{
	MyException(String message)
	{
		super(message);
	}

}
class TestMyException
{
	public static void main(String[] args) 
	{
		int x = 5, y = 1000;
		try
		{
			float z = (float)x / (float)y;
			if(z < 0.01)
			{
				throw new MyException("Number is too small");
			}
		}
		catch(MyException e)
		{
			System.out.println("Caught MyException");
			System.out.println(e.getMessage());
		}
		finally
		{
			System.out.println("java2all.com");
		}
	}
}

 
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.