Register Now

Login

Lost Password

Enter your email to reset your password.

BY Author

Java – The throw keyword

The throw keyword is used to generate exception explicitly.

Syntax

 throw ExceptionObject

Example – I

class ThrowDemo
{
    public static void main(String args[])
    {
        try
        {
            throw new ArithmeticException();
        }
        catch(ArithmeticException e)
        {
            System.out.println("Arithmetic Exception handled");
        }		
    }
}

Output

Arithmetic Exception Handled

Example – II

class ThrowStatement2 
{
    public static void main(String args[])
    {
        try
        {
            try
            {
                throw new ArithmeticException();
            }
            catch(ArithmeticException e)
            {
                throw e;
            } 		
        }
        catch(ArithmeticException e)
        {
            System.out.println("Arithmetic Exception Handled");
        }
    }
}

Output

Arithmetic Exception Handled

Note

The object that is to be thrown explicitly must be defined by Java or must inherit any exception class defined by Java.

 

Leave a reply