Can we write any code after throw statement in Java?

JavaObject Oriented ProgrammingProgramming

No, we can not place any code after throw statement, it leads to compile time error Unreachable Statement.

Throw keyword in Java

  • The throw keyword is used to throw an exception manually.
  • Whenever it is required to suspend the execution of the functionality based on the user-defined logical error condition, we will use this throw keyword to throw an exception.
  • We need to handle these exceptions using try and catch blocks.

Rules to use throw keyword in Java

  • The throw keyword must follow Throwable type of object.
  • The throw keyword must be used only in the method logic.
  • Since it is a transfer statement, we cannot place statements after throw statement. It leads to a compile-time error Unreachable code.
  • We can throw user-defined and predefined exceptions using throw keyword.

Example

Live Demo

public class ThrowKeywordDemo {
   public static void main(String[] args) {
      try {
         throw new ArithmeticException();
         System.out.println("In try block"); // compile-time error, unreachable statement
      } catch (Exception e) {
         System.out.println(e);
         e.printStackTrace();
      }
   }
}

The above code doesn't execute because there is a statement after a throw statement in the try block, it can cause the compile-time error. So we cannot put any statements after a throw statement in Java.

Output

unreachable statement
System.out.println("In try block");
raja
Published on 24-Jun-2019 18:57:49
Advertisements