by Dinesh Thakur Category: Exception Handling

You can also throw an exception explicitly. This is accomplished using the throw statement. A throw statement is executed to indicate that an exception has occurred. The exception that you throw using the throw statement can either be the standard system exception or the one that are created by you. The syntax of throw statement is as follows,

throw ObjectExpression;

The throw statement begins with the throw keyword which is then followed by an ObjectExpression which is an object that is instantiated from the class Throwable or any of its subclasses or extension of a class in the exception hierarchy.

The Throwable object can be instantiated either by using the new operator or by using a parameter into a catch clause. The syntax for creating Throwable object in the throw statement is

throw new ExceptionType(args);

where ExceptionType is the type of the exception object and args is the optional argument list for the constructor. For example,

throw new ArithmeticExeption("Divided by zero");

In the statement, the new keyword instantiates an object of class ArithmeticExeption and the string Divide by zero describes the exception. This string can be displayed by calling the getMessage () method of the class Throwable or when the object is used as an argument to print In () method. The throw keyword then throws this object.

Now let us examine the following program that demonstrates the use of throw statement,

public class ThrowClause

{
    static double divide (double num , double den)
    {
      if(den==0.0)
        throw new ArithmeticException("Denominator cannot be zero");
        else
          return (num/den);
    }
    public static void main(String[] args)
    {
        double x,y,z;
        try
        {
           x = 12.5 ;
           y = 0.0 ;
           z=divide(x,y);
           System.out.println(x + " / " + y +" = " + z);
        }
           catch(ArithmeticException e)
          {
              System.out.println(e.getMessage());
          }
     }
}

Throw Clause Example in Java



About Dinesh Thakur

Dinesh ThakurDinesh Thakur holds an B.SC (Computer Science), MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to Contact us.



Search Content