Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Exception handling
2.1.
The try-catch-finally block
2.2.
The try-finally block
3.
The finally Block
3.1.
Case 1: There is no exception in the code
3.1.1.
A return statement in the try block
3.1.2.
A System.exit(0) statement in the try block
3.2.
Case 2: Exception is handled by the catch block
3.3.
Case 3: Exception in finally block
4.
FAQs 
5.
Key Takeaways
Last Updated: Mar 27, 2024

The Finally Block in Java

Author Yashesvinee V
0 upvote
Crack Google SDE interview : Essential projects
Speaker
Saurav Prateek
SDE-2 @
20 Jun, 2024 @ 01:30 PM

Introduction

Every program we write has a possibility of not running successfully the first time due to errors. The program can be executed upon resolving those errors, be it syntax, logical or runtime. Exceptions are events that disrupt the normal execution on encountering any bugs or errors.

When an error occurs in a function, the function creates an exception object that is sent to the runtime system. The process of creating an exception object and handing it over to the runtime system is called throwing an exception. The exception object contains information about the error, its type and the state of the program when the error occurred.

Also see,  Swap Function in Java

Exception handling

Upon receiving the exception object, the runtime system searches for a method containing the code to handle the exception. This block of code is called an exception handler. The runtime system passes the exception to the appropriate handler when found. The program terminates if the system fails to find the correct exception handler from within its call stack.

Exception handling is an approach used by programmers to prevent the abrupt termination of a program. The exception handler chosen by the runtime system ‘catches’ the exception from the given code. The try, catch and finally blocks are the components used to write the exception handler statements.

The try-catch-finally block

  • The try block is to enclose the code that might throw an exception. If an exception occurs in the try block, it is handled by an exception handler component associated with it.
     
  • The catch block is used to associate a handler with the try block. The catch block comes immediately after the try block and handles the type of exception indicated by its argument: ExceptionType name.
     
  • The finally block always executes when the try block exits, irrespective of whether an exception has occurred or not.
     
try 
{ 
   // Statements to identify the exception
}
catch (ArithmeticException e)
{ 
   // Statements to handle the exception
}
finally
{ 
   // Statements 
}

The try-finally block

In some cases, the try block can be immediately followed by the finally block. So, a try-finally block is possible without a catch block. Here’s an example.

try 
{
  int a = 10, b = 0;
  int Result = a/b;
  System.out.println("Result = " + Result);
}

finally
{
  System.out.println("END");
}

 

 Output:

END
Exception in thread "main" java.lang.ArithmeticException: / by zero    

 

Must Read Static Blocks In Java. Also see, Duck Number in Java

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

The finally Block

Since the finally block executes regardless of an exception in the try block, it is helpful in more ways than one. The finally block can be used as a tool to prevent resource leaks. The code to close a file or any resources can be placed in a finally block to ensure that the job is done. It also prevents the cleanup code from bypassing the return, break or continue statements. It’s a good practice to implement the finally block, even when no exceptions are anticipated.

When used in different cases, the finally block results in different outputs. Let us discuss them in brief and understand their use.

Case 1: There is no exception in the code

When the try block encounters no exception in its code, the try block is executed and then the finally block. The catch block, if it exists, is ignored.

try
{ 
  int a = 10, b = 5;
  int Result = a/b;
  System.out.println("Result = " + Result);
}
catch
{ 
  System.out.println("The operation is not possible with b = 0");
}
finally
{ 
  System.out.println("END");
}

 

Output:

Result = 2
END

A return statement in the try block

A subroutine uses a return statement to return to the method that called it. If the try block contains a return statement and has a finally block following it, the finally block is first executed, and then the control returns to the calling method.

public static void main(String[] args)  {
  division();
  System.out.println("-----------------");
}
public static void division() {
try
{ 
  int a = 10, b = 5;
  int Result = a/b;
  System.out.println("Result = " + Result);
  return;
}
finally
{ 
  System.out.println("END");
}
}

 

Output:

Result = 2
END
----------------

A System.exit(0) statement in the try block

The System.exit(0) statement, unlike the return statement, completely exits the program. It means that the finally block will not be executed as well. However, if an exception occurs in the System.exit(0) method, then the finally block gets executed.

try
{ 
  int a = 10, b = 5;
  int Result = a/b;
  System.out.println("Result = " + Result);
  System.exit(0);
}
finally
{ 
  System.out.println("END");
}
}


Output:

Result = 5

Case 2: Exception is handled by the catch block

Now, let us assume that the try block finds an exception in its code. The catch block that contains the code to be executed on encountering an exception is chosen. If a finally block exists after the catch block, it is executed.

try
{ 
  int a = 10, b = 0;
  int Result = a/b;
  System.out.println("Result = " + Result);
}
catch
{
  System.out.println("The operation is not possible with b= 0");
}
finally
{ 
  System.out.println("END");
}

 

Output:

The operation is not possible with b = 0
END

Case 3: Exception in finally block

The finally block does not execute when there is an exception within the block itself. The exception encountered can be handled using another try-catch block within the finally block. 

int a = 10, b = 5;
try
{
  int Result = a*b;
  System.out.println("Product = " + Result);
}
finally
{ 
  System.out.println("Quotient = " + (a/b));
}
}

 

Output:

Product = 50
Exception in thread "main" java.lang.ArithmeticException: / by zero


Practice by yourself on java online compiler.

In conclusion, the finally block is not executed in the following cases:

  • Due to the death of a thread.
     
  • Due to the System.exit(0) statement in the try block.
     
  • The presence of an exception in the finally block.

 

Must Read Conditional Statements in Java and Hashcode Method in Java

FAQs 

Q: What is the difference between an error and an exception?

  • Errors occur at runtime, while exceptions may occur at runtime or compile time.
     
  • Errors are not recoverable, whereas exceptions can be recovered and handled by try-catch blocks.
     
  • Errors belong to the java.lang.Error package and exceptions belong to the java.lang.Exception package.
     

Q: What are the types of exceptions in Java?

  • Checked exceptions are compile-time exceptions that are checked by the compiler. If not handled, we get a compile error. A few examples of checked exceptions are IOException, ClassNotFoundException, InterruptionException, etc.
     
  • Unchecked Exceptions are not checked by the compiler, and do not throw a compile error on ignoring it. Examples of unchecked exceptions are NullPointer Exception, Arithmetic Exception, etc.

Key Takeaways

We all have encountered exceptions in the past or will face them in the future. Handling exceptions with finally is known to be more efficient and preferred, and hence, knowledge about it is essential. This blog covers the basics of exception handling and gives a detailed explanation of the finally block. We have also discussed the use of finally in different cases with examples.

Related Links:

Exceptions in Java- Hierarchy, types and Errors.

Checked and Unchecked Exceptions in Java

Exception handling with try-catch and finally

Introduction to Java

Check out the official Coding Ninjas Blog site and visit our Library for more.

Previous article
Java lang ExceptionInInitializerError
Next article
Final vs Finally vs Finalize
Live masterclass