Exception Handling Keywords

Exception Handling Keywords

In this tutorial, we are going to discuss exception handling keywords in java. We must place the risky code inside the try block and the corresponding exception handling code inside the catch block.

Exception Handling Keywords
try {
   //Risky code
} catch (Exception e) {
   //handling code
}
Without Exception handling code
Control Flow in try, catch
try {
   statement 1;
   statement 2;
   statement 3;
} catch (Exception e) {
   statement 4;
}
statement 5;

Case 1: If there is no exception

1,2,3,5 normal

Case 2: If there is an exception raised at statement 2 and the corresponding catch block matched.

1,4,5 normal termination.

Case 3: if an exception raised at statement 2 but the corresponding catch block is not matched

1 Abnormal termination.

Case 4: if an exception raised at statement 4 or statement 5 it is always abnormal termination.

The Methods to display Exception Information

The throwable class contains the following methods to display error information.

printStackTrace

It displays error information in the following format.

Name of Exception : Description

StackTace.

toString

It displays error in the following format.

Name of Exception : Description

getMessage

It displays error information in the following format.

Description

Exception Handling Keywords

Note

Default Exception handler always uses printStackTrace method only.

try with multiple catch blocks

The way of handling exceptions is valid from exception to exception. Hence for every exception, we should define corresponding catch blocks; try with multiple catch blocks is possible.

try {
   risky code
} catch (ArithmeticException e ) {
   //handler to A.E
} catch (NullPointerException e) {
   //handler for N.P.E
} catch(IOException e) {
   //handler for IOException
} catch(Exception e) {
   //handler for Exception
}

In the case of try with multiple catch blocks, the order of catch blocks is important. And it should be from child to parent; otherwise, Compiler Error. Saying Exception xxx has already been caught.

try {
   risky code
} catch (ArithmeticException e ) {  
  //Fine
} catch (Exception e){
}

try {
   risky code
} catch (Exception e ) {  
} catch (ArithmeticException e){ 
  //Error
}
C.E java.lang.ArithmeticException has already been caught

Suppose there is no chance of raising an exception in a try statement. In that case, we are not allowed to maintain a catch block for that exception violation leads to compile-time error, but this rule is applicable only for fully checked exceptions.

try {
   System.out.println("Hi");
} catch (ArithmeticException e) {
}

try {
   System.out.println("Hi");
} catch (Exception e){
}

try {
   System.out.println("Hi");
} catch (IOException e) {
}
C.E: java.io.IOException is never thrown in body of corresponding try statement

try {
   System.out.println("Hi");
} catch (InterruptedException e) {
}
C.E: InterruptedException is never thrown in body of corresponding try statement
finally
  • It is not recommended to place cleanup code inside try statement because there is no guarantee for the execution of all statements inside try block.
  • It is not recommended to maintain cleanup code within the catch block because the catch blocks won’t be executed if there is no execution.
  • We required a block to maintain cleanup code which should always execute irrespective of whether the exception is raised or not whether it is handled or not. Such block is nothing but “finally block.”

Hence the main objective of the finally block is to maintain cleanup code.

try {
   //open the database connection
   //read the data
} catch (Exception e) {
} finally {
   close the Connection
}
try {
   System.out.println("try");
} catch (ArithmeticException e) {
   System.out.println("catch");
} finally {
   System.out.println("finally");
}

Output

try
finally
Normal
Termination
try {
   System.out.println(10/0);
} catch (ArithmeticException e) {
   System.out.println("catch");
} finally {
   System.out.println("finally");
}

Output

catch
finally
Normal
Termination
try {
   System.out.println(10/0);
} catch (NullPointerException e) {
   System.out.println("catch");
} finally {
   System.out.println("finally");
}

Output

finally
Abnormal termination 

Hence finally block should always execute irrespective of whether the execution is raised or not raised or handled or not handled. The finally block won’t be executed if the system itself exists(JVM shutdown) i.e., in the case of System.exit() finally, the block won’t be executed.

try {
   System.out.println("Hi");
   System.exit(0);
} catch (ArithmeticException e) {
   System.out.println("catch");
} finally {
   System.out.println("finally");
}

Output

Hi
Difference Between final, finally, finalize
final
  • It is the modifier applicable for classes methods and variables. For final classes, we can’t create child classes, i.e., inheritance is not possible.
  • final() methods can’t be override in child classes for final variables reassignments is not possible because they are constants.
finally

It is a block associated with try-catch. The main objective of the finally block is to maintain cleanup code, which should execute always.

finalize

It is a method that the “Garbage Collector” should be executed just before destroying an object. The main objective of finalize method is to maintain cleanup code.

Note

When compared with finalize, finally is always recommended to maintain cleanup code because there is no guarantee for the exact behavior of “Garbage Collector” it is Virtual Machine Dependent.

Control flow in try – catch – finally

The following program will demonstrate the control flow in different cases.

public class ExceptionDemo {
   public static void main(String arg[]) {
      try {
         statement1;
         statement2;
         statement3;
      } catch (Exception e) {
         statement4;
      } finally {
         statement5;
      }
      statement6;
   }
}

Case 1: if there is no exception, then statements 1, 2, 3, 5, 6 will execute with normal termination.

Case 2: if an exception is raised at statement-2 and the corresponding catch block matched, then statements 1, 4, 5, 6 will execute with normal termination.

Case 3: if an exception is raised at statement-2, but the corresponding catch block is not matched, statements 1, 5, 6 will execute with abnormal termination.

Case 4: if an exception is raised at statement-2 and while executing the corresponding catch block at statement–4, an exception is raised, then statement 1, 5 will execute with abnormal termination.

Case 5: if an exception is raised at statement-5 or statement-6, it is always an abnormal condition. Control flow in nested try-catch – finally

Control flow in nested try – catch – finally

The following program will demonstrate the flow of nested try–catch– finally.

try {
   statement 1;
   statement 2;
   statement 3;
   try {
      statement 4;
      statement 5;
      statement 6;
   } catch (Exception e) {
      statement 7;
   } finally {
      statement 8;
   }
   statement 9;
} catch (Exception e) {
   statement 10;
} finally {
   statement 11;
}
statement 12;

Case 1: if there is no exception, then statements 1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12 will execute with normal termination.

Case 2: if an exception is raised at statement-2 and the corresponding catch block matched, then statements 1, 10, 11, 12 will execute with normal termination.

Case 3: if an exception is raised at statement-2, but the corresponding catch block is not matched, statements 1, 11, 12 will execute with abnormal termination.

Case 4: if an exception is raised at statement-5 and the corresponding inner catch has matched, statements 1, 2, 3, 4, 7, 8, 9, 11, 12 will execute with normal termination.

Case 5: if an exception is raised at statement-5 and the inner catch has not matched, but the outer catch has matched, then the statements 1, 2, 3, 4, 8, 10, 11, 12 will execute with normal termination.

Case 6: if an exception is raised at statement-5, but the inner and outer catch blocks are not matched, then statements 1, 2, 3, 4, 8, 11 will execute with abnormal termination.

Case 7: if an exception is raised at statement-7 and

  • If the outer catch block has matched, then the statements 1, 2, 3, – – – 8, 10, 11, 12 will execute with normal termination.
  • If the outer catch block has not matched, then the statements 1, 2, 3, – – – 8, 11 will execute with abnormal termination.

Case 8: if an exception raised at statement-8 and

  • If the outer catch has matched, then the statements 1, 2, 3, – – – will execute with normal termination.
  • If the outer catch has not matched, then the statements 1, 2, 3, – – – 11 will execute with abnormal termination.

Case 9: if an exception raised at statement-9 and

  • If the outer catch has matched, then the statements 1, 2, 3 – – -8, 10, 11, 12 will execute with normal termination.
  • If the outer catch has not matched, then the statements 1, 2, 3 – – -8, 11 will execute with abnormal termination.

Case 10: If an exception is raised at statement-10, it is always abnormal termination, but before termination is compulsory, the finally block should be executed.

Case 11: If an exception is raised at statement-11 or 12, it is always abnormal termination.

throw

By using the throw keyword, we can hand – over the exception object to the JVM. The output of the following two programs is the same.

public class Test {
   public static void main(String arg[]) {
      System.out.println(10/0);
   }
}
public class Test {
   public static void main(String arg[]) {
      throw new ArithmeticException ("/ by zero...!");
   } 
}

Here in the first case, the main method is responsible for creating an exception object and hand–over that object to the JVM.

In the second case, we created an object explicitly and hand – over that object to the JVM programmatically by throw keyword.

Syntax

throw e;
Where ‘e’ --> Any throwable object 

E.g

public class Test {
   public static void main(String arg[]) {
      throw new Test();
   }
}
C.E: Incompatible type found 
public class Test {
   static ArithmeticException e = new ArithmeticException();
   public static void main(String arg[]) {
      throw e;
   }
}
Exception in thread “main” java.lang.ArithmeticException: / by zero

Here Explicitly, we created an object to the ArithmeticExcption class, and that object was thrown by a throw to the JVM.

public class Test {
   static ArithmeticException e;
   public static void main(String arg[]) {
      throw e;
   }
}
Exception in thread “main” java.lang.NullPointerException

Here we didn’t create an Object to the AritmeticExcepiton class. We just created a reference, so the reference variable is not pointing to any object, and we thrown only the reference variable. That’s why only it shows NullPointerException.

After throw keyword, we are not allowed to place any statements directly; otherwise, we will get a compile-time error.

public class Test {
   public static void main(String arg[]) {
      throw new ArithmeticException();
      System.out.println("After throw statement...!");
  }
}
C.E: Unreachable code

Directly in the sense indirectly we can place any statements after throw. See the following example.

public class Test {
   public static void main(String arg[]) {
      if(false) {
         throw new ArithmeticException();
      } else {
         System.out.println("After throw statement...!");
      }
   }
}
throws

If our code may be a chance of raising checked exception then compulsory we should handle that checked exception either by using try, catch or we have to delegate that responsibility to the caller using throws keyword otherwise C.E saying

UnreportedException : XXXException must be caught or declared to be thrown

public class Test {
   public static void main(String arg[]) {
      Thread.sleep(1000);
   }
}
C.E: UnreportedException : java.lang.InterruptedException must be caught or declared to be thrown

We can resolve this problem either by using try-catch or by using the throws keyword as follows.

public class Test {
   public static void main(String arg[]) {
      try {
         Thread.sleep(1000);
      }
      catch (InterruptedException e) {
      }
   }
}
public class Test {
   public static void main(String arg[])throws InterruptedException {
      Thread.sleep(1000);
   }
}

Hence the main objective of the throws keyword is to delegate the responsibilities of exception handling to the caller.

public class Test {
   public static void main(String arg[]) throws InterruptedException {
      doStuff();
   }
   public static void doStuff() throws InterruptedException {
      doMoreStuff();
   }
   public static void doMoreStuff() throws InterruptedException {
      Thread.sleep(500);
      System.out.println("I am in office");
   }
}

If we are not taking at least one throws keyword, we will get Compiler Error. If the parent class constructor throws some checked exception, then the child class constructor must throw the same checked exception or its parent other wise compiler error.

Summary of Exception Handling Keywords

try: To maintain risky code.

catch: To maintain exception handling code.

finally: To maintain cleanup code.

throw: To hand – over exception object to the JVM programmatically.

throws: To delegate the responsibilities of exception handling to the caller.

Exception Handling Keywords

Scroll to top