Java Program to Use finally block for Catching Exceptions


Finally Block for Catching Exceptions: An Overview

Programming is an exciting field that requires careful attention to detail, especially when it comes to handling exceptions. Simply put, exceptions are unforeseen circumstances that can disrupt the flow of our program. When an exception occurs, it's important to address it promptly to prevent unexpected outcomes.

In Java, there are several ways to handle exceptions, but one of the most effective methods is using Try, Catch, and Finally blocks.

In this article, we will delve into the world of Java Exception Handling and explore how to use the finally block to catch exceptions.

Exception Handling in Java

A key idea in computing is exception handling, which enables us to deal with potential runtime errors that may occur while our code is being executed. These mistakes can take on a number of different shapes, including ClassNotFoundException, IOException, SQLException, RemoteException, and others. By including an exception handling mechanism in our programs, we can make sure that the application keeps running as intended even when an exception happens.

Java Finally Block

The Java finally block is a critical component that allows developers to execute vital code, such as closing connections, in a program. Unlike other code blocks, the finally block is executed every time, regardless of whether an exception was handled or not. As a result, the finally block is a reliable place to include statements that must be executed no matter what.

In Java programs, the finally block is invariably placed following the try-catch block. Its main goal is to make cleanup code additions possible, like closing files or connections, so resources are relinquished properly. Developers can ensure that essential statements are always performed, even if an exception is thrown, by inserting them in the finally block.

Usage of Java Finally

The finally block is used in a number of situations, including −

Situation 1 − When There is no Exception

The finally block executes following the try block as the program runs without any issues.

Algorithm

  • Step 1 − The program structures a main function and a class named Tutorialspoint.

  • Step 2 − The main operation establishes a try-catch-finally block. Both the code to execute and the code to execute in the catch block in the event of an exception are in the try and catch blocks, respectively.

  • Step 3 − The try block just prints "within try block" in this instance and divides the number 40 by two without throwing an exception. As a result, the catch block is not used.

  • Step 4 − The finally block is always carried out, whether or not an exception is thrown. Specifically, it prints, "Finally: I can code."

Example 1

Let us look at example for better understanding.

import java.io.*;
public class Tutorialspoint {
   public static void main(String[] args){
      try {
         System.out.println("within try block");
         // Not throw any exception
         System.out.println(40 / 2);
      }
      
      // Not execute in this case
      catch (ArithmeticException e) {
         System.out.println("Arithmetic Exception");
      }
      
      // Always execute
      finally {
         System.out.println(
         "finally : i can code.");
      }
   }
} 

Output

within try block
20
finally : i can code.

Situation 2 − When an Exception is Caught and Handled by the Catch Block, with Finally Block Execution

In this scenario, the program encounters an exception but the catch block handles it. The finally block is the next to run after the catch block. Whether or whether an exception was caught, the finally block always gets to work.

Algorithm

  • Step 1 − The program goes into the try block and tries to run its instructions.

  • Step 2 − When the program tries to divide 40 by 0, an arithmetic exception is thrown.

  • Step 3 − The catch block catches the exception and executes its logic, producing a message indicating that the exception has been handled.

  • Step 4 − Lastly, irrespective of whether an exception was caught or not, the finally block is run, printing a message showing that it can always execute.

Example 2

The catch block handles the exception and the finally block always executes. The output displays the text from the try, catch, and finally blocks.

import java.io.*;
public class Tutorialspoint {
   public static void main(String[] args){
      try {
         System.out.println("inside try block");
         // Throw an Arithmetic exception
         System.out.println(40 / 0);
      }
      
      // catch an Arithmetic exception
      catch (ArithmeticException e) {
         System.out.println(
         "catch : exception handled.");
      }
      
      // Always execute
      finally {  
         System.out.println("finally : i can code.");
      }
   }
}

Output

inside try block
catch : exception handled.
finally : i can code.

Situation 3 − Exception not Handled by Catch Block, but Finally Block Executed

In this scenario, the program encounters an exception but the catch block is not able to handle it, so the program terminates abnormally after the finally block is executed. However, the finally block is still executed successfully.

Conclusion

To sum it up, when dealing with unforeseen circumstances that can disrupt the flow of a program in Java, it's essential to have an effective method of exception handling. The Try, Catch, and Finally blocks are critical tools in handling exceptions, and the finally block, in particular, allows developers to execute crucial code, such as closing connections.

By using the finally block, programmers can ensure that vital statements are executed every time, regardless of whether an exception.

Updated on: 15-May-2023

135 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements