πŸŽ‰ Special Offer !    Code: GET300OFF    Flat β‚Ή300 OFF on every Java Course
Grab Deal πŸš€

"throw" Keyword in Java  


Introduction

  • The throw keyword is used in Java to explicitly create and throw an exception object.
  • We can throw either checked or unchecked exception.
    • If it's a checked exception, the method must declare it using throws or handle it with try-catch.
    • If it's an unchecked exception, no declaration is needed.
  • Use :
    • To manually signal that an error or exceptional condition has occurred.
    • Mostly used to throw custom exceptions defined by the user.
    • Helps in writing robust programs by handling abnormal conditions properly.
  • Syntax :
    • throw throwableObject;
    • Here, throwableObject is an instance of the Throwable class or its subclass (like Exception or Error).
  • Example :
    • throw new ArithmeticException("You cannot divide by zero");
      • Directly creates and throws a new exception object.
    • ArithmeticException ae = new ArithmeticException("You cannot divide by zero");
      throw ae;
      • First creates an exception object, stores it in a variable, then throws that object.
  • Program :
    • import java.util.Scanner;
      
      public class ThrowDemo
      {
          void m1()
          {
              Scanner sc = new Scanner(System.in);
      
              System.out.println("Enter no1");
              int no1 = sc.nextInt();
      
              System.out.println("Enter no2");
              int no2 = sc.nextInt();
      
              try
              {
                  int res = no1/no2;
                  System.out.println("Result : "+res);
              }
              catch (Exception e)
              {
                  System.out.println("Exception caught: " + e.getMessage());
              }
          }
          public static void main(String[] args)
          {
              ThrowDemo td = new ThrowDemo();
              td.m1();
          }
      }
    • Flow of Program:
      • Taking user input and division β†’ If user provides no2 = 0, Java will throw an ArithmeticException.
      • With try-catch block β†’ The catch block catches the exception and prints the message.
      • Without try-catch block inside m1() β†’
        • If we dont handle the exception object using try-catch block, it will be passed to the caller method (main() in this case).
        • If main() also doesn't handle it either, the exception will propagate to the JVM.
        • JVM will print the stack trace and terminate the program abruptly
    • Points to Note:
      • Here we are throwing a generic Exception. In real applications, it is better to throw specific exception types.
      • Its recommended to use try-catch block to handle the exception object created using throw keyword.

Points to remember for "throw" Keyword:
  1. The throw keyword creates only a single exception object at a time, not multiple.
  2. It must be used inside a method or a block of code.
  3. It must be the last statement in the block where it is used.
  4. In real-world projects, the throw keyword is mostly used with custom exceptions.
  5. Using throw keyword, only exception object can be thrown, not classes or literals.