๐ŸŽ‰ Special Offer !    Code: GET300OFF    Flat โ‚น300 OFF on every Java Course
Grab Deal ๐Ÿš€

try-catch Block in Java  


Introduction

  • Definition:
    • try and catch are blocks in Java used for exception handling.
    • They allow developers to handle runtime exceptions gracefully without crashing the program.

  • try block:
    • try block contains the code that may throw an exception.
    • In simple words we can say, it contains the risky code that can cause an exception.
    • Syntax:
      try
      {
          // Risky code that may throw an exception
      }
  • catch block:
    • catch block is used to handle the exception thrown by the try block.
    • In simple words we can say, it contains the code that will handle the exception if it occurs in try block.
    • Syntax:
      catch(ExceptionClassType ref_variable)
      {
          // Code to handle exception
      }

  • Example:
    • Lets take an example in which we will take two numbers as input from the user and divide them.
    • First we will create program without using try-catch block.
    • import java.util.Scanner;
      
      public class MainApp1
      {
          public static void main(String[] args)
          {
              System.out.println("----- App Started -----");
      
              Scanner sc = new Scanner(System.in);
      
              System.out.println("Enter no 1");
              int no1 = sc.nextInt();
      
              System.out.println("Enter no 2");
              int no2 = sc.nextInt();
      
              int res = no1 / no2;
              System.out.println("Result : "+res);
      
              System.out.println("----- App Finished Successfully -----");
          }
      }
    • If the user enters 0 as the second number, it will throw an ArithmeticException and the program will terminate abnormally.
      • ----- App Finished Successfully ----- will not be printed as the program is terminated abnormally.
    • Now we will modify the above program to handle the exception using try-catch block.
    • import java.util.Scanner;
      
      public class MainApp1
      {
          public static void main(String[] args)
          {
              System.out.println("----- App Started -----");
      
              Scanner sc = new Scanner(System.in);
      
              try
              {
                  System.out.println("Enter no 1");
                  int no1 = sc.nextInt();
      
                  System.out.println("Enter no 2");
                  int no2 = sc.nextInt();
      
                  int res = no1 / no2;
                  System.out.println("Result : "+res);
              }
              catch(ArithmeticException ae)
              {
                  System.out.println("Exception Occured : "+ae);
              }
      
              System.out.println("----- App Finished Successfully -----");
          }
      }
    • Here, we have wrapped the risky code inside the try block and handled the ArithmeticException in the catch block.
    • Now, if the user enters 0 as the second number, it will throw an ArithmeticException, but instead of terminating the program abnormally, it will jump to the catch block and print the exception message.

Points to remember for try-catch block:
  1. try cannot be used alone; it must be followed by catch or finally.
    • Syntax :
      try
      {
          // Risky code that may throw an exception
      }
      catch(ExceptionClassType ref_variable)
      {
          // Code to handle exception
      }
      try
      {
          // Risky code that may throw an exception
      }
      catch(ExceptionClassType ref_variable)
      {
          // Code to handle exception
      }
      finally
      {
          // Code that will always execute (explained later)
      }
  2. The exception object (i.e., the reference variable in the catch block) contains detailed information about the exception, such as the :
    • exception class name
    • message / description
    • stack trace
  3. If an exception occurs in try block, then only program jumps to the catch block, but if there is not exception in try block, then catch block is skipped or will not be executed. Try Catch Block Execution in Java

Different ways to print exception object:
  1. Using getMessage()
    • Prints only the exception message.
    • catch (Exception e)
      {
          System.out.println(e.getMessage());
      }
  2. Using toString()
    • Prints the exception class name along with the message.
    • catch (Exception e)
      {
          System.out.println(e.toString());
      }
  3. Using printStackTrace()
    • Prints full stack trace including the line number where the exception occurred.
    • catch (Exception e)
      {
          e.printStackTrace();
      }