Back Button
Back to Chapter
Introduction
No items found.
Collapse_Icon
Table of Contents

The finally keyword:

Java supports another statement known as the finally statement that contains all the crucial statements that must be executed whether an exception occurs or not. The statements present in this block will always execute regardless of whether an exception occurs in a try block or not such as closing a connection, stream, etc.

It may be added immediately after the try block or after the last catch block shown as follows:

Syntax 1:

try
{
 statement;  // generates an exception
}
finally
{
 statement; // final statement
}

Syntax 2:

try
{
 statement;  // generates an exception

}
catch( Exception-type e)
{
 statement; // processes the exception
}
catch( Exception-type e)
{
 statement; // processes the exception
}
finally
{
statement; // final statement
}

Example:

class FinallyExample {
 public static void main(String args[]) {
   try {
     int num = 25 / 5;
     System.out.println(num);
   } catch (NullPointerException e) {
     System.out.println(e);
   } finally { // finally used after catch block
     System.out.println("finally block is always executed");
   }
   System.out.println("rest of the code...");
 }
}

/*OUTPUT:
finally block is always executed
rest of the code... */

The throw keyword:

The Java throw keyword is used to explicitly throw a single exception. When we throw an exception, the flow of the program moves from the try block to the catch block. The throw keyword is used to create a custom error. The throw statement is used together with an exception type.

Example:

class ThrowExample {
 public static void divideByZero() {

   // throw an exception
   throw new ArithmeticException("Trying to divide by 0");
 }

 public static void main(String[] args) {
   divideByZero();
 }
}
/*OUTPUT:
Exception in thread "main" java.lang.ArithmeticException: Trying to divide by 0
at ThrowExample.divideByZero(ThrowExample.java:5)
at ThrowExample.main(ThrowExample.java:9) */