Exception Handling Keywords in Java

There are five keywords used in Java for exception handling. They are:
i. try
ii. catch
iii. throw
iv. throws
v. finally

The try block

The try block contains the code that might throw an exception. The try block contains at least one catch block or finally block.

The catch block

A catch block must be declared after try block. It contains the error handling code. A catch block executes if an exception generates in corresponding try block.

Syntax

try
{
      //code that cause exception;
}
catch(Exception_type  e)
{
      //exception handling code
}


Example : An examples to uses try and catch block in java

class TryCatchDemo
{
        public static void main(String args[])
        {
             int a  = 30, b = 3, c = 3;
             int result1, result2;
             try
             {
                   result1 = a / (b - c);
             }
             catch(ArithmeticException ae)
             {
                   System.out.println("Divided by zero: "+ae);
             }
             result2 = a / (b + c);
             System.out.println("Result2 = "+result2);
        }
}


Output :
Divided by zero: java.lang.ArithmeticException: / by zero
Result2 = 5

Example : A program to illustrate the uses of try and catch block

class ExceptionDemo
{
      public static void main(String args[])
      {
          try
          {
                int arr[] = new int[5];
                arr[2] = 5;
                System.out.println("Access element two: " + arr[2]);
                arr[7] = 10;
                System.out.println("Access element seven: "+ arr[7]);
          }
          catch(ArrayIndexOutOfBoundsException e)
          {
                 System.out.println("Exception thrown:" + e);
          }
          System.out.println("End of the block");
      }
}


Output :
Access element two: 5
Exception thrown: java.lang.ArrayIndexOutOfBoundsException: 7
End of the block

Multiple catch blocks
If more than one exception is generated by the program then it uses multiple catch blocks. A single try block can contain multiple catch blocks.

Syntax

try
{
      // code which generate exception
}
catch(Exception_type1 e1)
{
      //exception handling code
}
catch(Exception_type2 e2)
{
      //exception handling code
}


Example : A program illustrating multiple catch block using command line argument

public class MultipleCatch
{
      public static void main(String args[])
      {
              try
              {
                   int a = Integer.parseInt(args[0]);
                   int b = Integer.parseInt(args[1]);
                   int c = a / b;
                   System.out.println("Result = "+c);
              }
              catch(ArithmeticException ae)
              {
                    System.out.println("Enter second value except zero.");
              }
              catch (ArrayIndexOutOfBoundsException ai)
              {
                     System.out.println("Enter at least two numbers.");
              }
              catch(NumberFormatException npe)
              {
                      System.out.println("Enter only numeric value.");
              }
      }
}


Output:
10       5
Result = 2

10       0
Enter second value except zero.

5
Enter at least two numbers.

10        a
Enter only numeric value.

The finally block

  • The code present in finally block will always be executed even if try block generates some exception.
  • Finally block must be followed by try or catch block.
  • It is used to execute some important code.
  • Finally block executes after try and catch block.

Syntax

try
{
      // code
}
catch(Exception_type1)
{
      // catch block1
}
Catch(Exception_type2)
{
      //catch block 2
}
finally
{
      //finally block
      //always execute
}


Example : A program to implement finally block

class FinallyTest
{
      public static void main(String args[])
      {
            int arr[] = new int[5];
            try
            {
                  arr[7] = 10;
                  System.out.println("Seventh element value: " + arr[7]);
            }
            catch(ArrayIndexOutOfBoundsException ai)
            {
                  System.out.println("Exception thrown : " + ai);
            }
            finally
            {
                  arr[0] = 5;
                  System.out.println("First element value: " +arr[0]);
                  System.out.println("The finally statement is executed");
            }
      }
}


Output:
Exception thrown: java.lang.ArrayIndexOutOfBoundsException: 7
First element value: 5
The finally statement is executed

The throw keyword in Java

  • The throw keyword in Java is used to explicitly throw our own exception.
  • It can be used for both checked and unchecked exception.
Syntax:
throw new Throwable_subclass;

Example : A program to illustrate throw keyword in java

public class ThrowTest
{
    static void test()
    {
          try
          {
                throw new ArithmeticException("Not valid ");
          }
          catch(ArithmeticException ae)
          {
                System.out.println("Inside test() ");
                throw ae;
          }
    }
    public static void main(String args[])
    {
          try
          {
                test();
          }
          catch( ArithmeticException ae)
          {
                System.out.println("Inside main(): "+ae);
          }
    }
}


Output:
Inside test()
Inside main(): java.lang.ArithmeticException: Not valid

The throws keyword in Java

  • The throws keyword is generally used for handling checked exception.
  • When you do not want to handle a program by try and catch block, it can be handled by throws.
  • Without handling checked exceptions program can never be compiled.
  • The throws keyword is always added after the method signature.

Example : A program to illustrate uses of throws keyword

public class ThrowsDemo
{
     static void throwMethod1() throws NullPointerException
     {
          System.out.println ("Inside throwMethod1");
          throw new NullPointerException ("Throws_Demo1");
     }
     static void throwMethod2() throws ArithmeticException
     {
          System.out.println("Inside throwsMethod2");
          throw new ArithmeticException("Throws_Demo2");
     }
     public static void main(String args[])
     {
          try
          {
               throwMethod1();
          }
          catch (NullPointerException exp)
          {
               System.out.println ("Exception is: " +exp);
          }
                try
                {
                       throwMethod2();
                }
                catch(ArithmeticException ae)
                {
                       System.out.println("Exception is: "+ae);
                }
     }
}


Output:
Inside throwMethod1
Exception is: java.lang.NullPointerException: Throws_Demo1
Inside throwsMethod2
Exception is: java.lang.ArithmeticException: Throws_Demo2

Difference between throw and throws keyword in Java

ThrowThrows
It is used to throw own exception.It is used when program does not handle exception via try block.
It handles explicitly thrown exceptions.It handles all exceptions generated by program.
Cannot throw multiple exceptions.Declare multiple exception e.g.
public void method() throws, IOException, SQLException.
It is used within the method. It is used within method signature.