What are unreachable catch blocks in Java?

JavaObject Oriented ProgrammingProgramming

A block of statements to which the control can never reach under any case can be called as unreachable blocks. Unreachable blocks are not supported by Java. The catch block mentioned with the reference of Exception class should and must be always last catch block because Exception is the superclass of all exceptions. When we are keeping multiple catch blocks, the order of catch blocks must be from most specific to most general ones. i.e subclasses of Exception must come first and superclasses later. If we keep superclasses first and subclasses later, the compiler will throw an unreachable catch block error.

Syntax

try {
   // statements
} catch(Exception e) {
   System.out.println(e);
} catch(NumberFormatException nfe) { //unreachable block. Not supported by Java, leads to an error.
   System.out.println(nfe);
}

A catch clause is considered reachable by the compiler if both of the following conditions are true

  • A checked exception that is thrown in the try block is assignable to the parameter of C.
  • There is no previous catch clause whose parameter type is equal to or a supertype of the parameter type of C

A catch clause is considered reachable by the compiler can be unreachable if both of the following conditions are true

  • The catch clause parameter type E does not include any unchecked exceptions.
  • All exceptions that are thrown in the try block whose type is a (strict) subtype of E are already handled by previous catch clauses.

Example

Live Demo

public class UnreachableBlock{
   public static void main(String[] args) {
      try {
         int i = Integer.parseInt("abc"); //This statement throws NumberFormatException
      } catch(NumberFormatException nfe) {
         System.out.println("This block handles NumberFormatException");
      } catch(Exception e) {
         System.out.println("This block handles all exception types");
      } catch (Throwable t) {
         System.out.println("Throwable is super class of Exception");
      }
   }
}

Output

This block handles NumberFormatException
raja
Published on 20-Jun-2019 11:51:50
Advertisements