Is there any way to skip finally block even if some exception occurs in exception block using java?


An exception is an issue (run time error) occurred during the execution of a program. When an exception occurred the program gets terminated abruptly and, the code past the line that generated the exception never gets executed.

Try, catch, finally blocks

To handle exceptions Java provides a try-catch block mechanism.

A try/catch block is placed around the code that might generate an exception. Code within a try/catch block is referred to as protected code.

Syntax

try {
   // Protected code
} catch (ExceptionName e1) {
   // Catch block
}

When an exception raised inside a try block, instead of terminating the program JVM stores the exception details in the exception stack and proceeds to the catch block.

A catch statement involves declaring the type of exception you are trying to catch. If an exception occurs in the try block it is passed to the catch block (or blocks) that follows it.

If the type of exception that occurred is listed in a catch block, the exception is passed to the catch block much as an argument is passed into a method parameter.

Example

import java.io.File;
import java.io.FileInputStream;
public class Test {
   public static void main(String args[]){
      System.out.println("Hello");
      try{
         File file =new File("my_file");
         FileInputStream fis = new FileInputStream(file);
      }catch(Exception e){
         System.out.println("Given file path is not found");
      }
   }
}

Output

Given file path is not found

Finally bock and skipping it

The finally block follows a try block or a catch block. A finally block of code always executes, irrespective of occurrence of an Exception. You cannot skip the execution of the final block. Still if you want to do it forcefully when an exception occurred, the only way is to call the System.exit(0) method, at the end of the catch block which is just before the finally block.

Example

public class FinallyExample {
   public static void main(String args[]) {
      int a[] = {21, 32, 65, 78};
      try {
         System.out.println("Access element three :" + a[5]);
      } catch (ArrayIndexOutOfBoundsException e) {
         System.out.println("Exception thrown :" + e);
         System.exit(0);
      } finally {
         a[0] = 6;
         System.out.println("First element value: " + a[0]);
         System.out.println("The finally statement is executed");
      }
   }
}

Output

Exception thrown
:java.lang.ArrayIndexOutOfBoundsException: 5

Updated on: 03-Jul-2020

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements