Java Throws Keyword


Any method capable of causing exceptions must list all the exceptions possible during its execution, so that anyone calling that method gets a prior knowledge about which exceptions to handle. A method can do so by using the throws keyword.

Syntax

type method_name(parameter_list) throws exception_list
{
 //definition of method
}

Example

class pqr
{
    public void divide_m() throws ArithmeticException  // throw keyword
    {
        int x=22;
        int y=0;
        int z;
        z=x/y;
    }
}
public class NewMain {

    public static void main(String[] args) {
       
        pqr obj = new pqr(); // Create object of PQR class
        try
        {
            obj.divide_m();  // Calling   
        }
        catch(ArithmeticException e)
        {
            System.out.println("Caught the exception="+e);
        }
        
    }
}
Output
Caught the exception=java.lang.ArithmeticException: / by zero

Share this article on