0% found this document useful (0 votes)
29 views6 pages

Understanding Java Finally Block

The document discusses the finally block in Java exception handling. It explains that a finally block contains statements that must execute whether an exception occurs or not, such as closing connections. It provides the syntax of a try-catch-finally block and examples showing that the finally block executes after the try block if no exception occurs, and after the catch block if an exception occurs and is handled. It also discusses some key properties and use cases of the finally block.

Uploaded by

Josphat Erick
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views6 pages

Understanding Java Finally Block

The document discusses the finally block in Java exception handling. It explains that a finally block contains statements that must execute whether an exception occurs or not, such as closing connections. It provides the syntax of a try-catch-finally block and examples showing that the finally block executes after the try block if no exception occurs, and after the catch block if an exception occurs and is handled. It also discusses some key properties and use cases of the finally block.

Uploaded by

Josphat Erick
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Java Finally block – Exception handling

By Chaitanya Singh | Filed Under: Exception Handling

In the previous tutorials I have covered try-catch block and nested try block. In this guide, we
will see finally block which is used along with try-catch.
A finally block contains all the crucial statements that must be executed whether exception
occurs or not. The statements present in this block will always execute regardless of whether
exception occurs in try block or not such as closing a connection, stream etc.

Syntax of Finally block


try {
//Statements that may cause an exception
}
catch {
//Handling exception
}
finally {
//Statements to be executed
}

A Simple Example of finally block


Here you can see that the exception occurred in try block which has been handled in catch block,
after that finally block got executed.

class Example
{
public static void main(String args[]) {
try{
int num=121/0;
[Link](num);
}
catch(ArithmeticException e){
[Link]("Number should not be divided by zero");
}
/* Finally block will always execute
* even if there is no exception in try block
*/
finally{
[Link]("This is finally block");
}
[Link]("Out of try-catch-finally");
}
}

Output:

Number should not be divided by zero


This is finally block
Out of try-catch-finally

Few Important points regarding finally block


1. A finally block must be associated with a try block, you cannot use finally without a try block.
You should place those statements in this block that must be executed always.

2. Finally block is optional, as we have seen in previous tutorials that a try-catch block is
sufficient for exception handling, however if you place a finally block then it will always run
after the execution of try block.

3. In normal case when there is no exception in try block then the finally block is executed after
try block. However if an exception occurs then the catch block is executed before finally block.

4. An exception in the finally block, behaves exactly like any other exception.

5. The statements present in the finally block execute even if the try block contains control
transfer statements like return, break or continue.
Lets see an example to see how finally works when return statement is present in try block:

Another example of finally block and return statement

You can see that even though we have return statement in the method, the finally block still runs.

class JavaFinally
{
public static void main(String args[])
{
[Link]([Link]());
}
public static int myMethod()
{
try {
return 112;
}
finally {
[Link]("This is Finally block");
[Link]("Finally block ran even after return statement");
}
}
}

Output of above program:

This is Finally block


Finally block ran even after return statement
112

To see more examples of finally and return refer: Java finally block and return statement
.
Cases when the finally block doesn’t execute
The circumstances that prevent execution of the code in a finally block are:
– The death of a Thread
– Using of the System. exit() method.
– Due to an exception arising in the finally block.

Finally and Close()


close() statement is used to close all the open streams in a program. Its a good practice to use
close() inside finally block. Since finally block executes even if exception occurs so you can be
sure that all input and output streams are closed properly regardless of whether the exception
occurs or not.

For example:

....
try{
OutputStream osf = new FileOutputStream( "filename" );
OutputStream osb = new BufferedOutputStream(opf);
ObjectOutput op = new ObjectOutputStream(osb);
try{
[Link](writableObject);
}
finally{
[Link]();
}
}
catch(IOException e1){
[Link](e1);
}
...

Finally block without catch


A try-finally block is possible without catch block. Which means a try block can be used with
finally without having a catch block.

...
InputStream input = null;
try {
input = new FileInputStream("[Link]");
}
finally {
if (input != null) {
try {
[Link]();
}catch (IOException exp) {
[Link](exp);
}
}
}
...

Finally block and [Link]()


[Link]() statement behaves differently than return statement. Unlike return statement
whenever [Link]() gets called in try block then Finally block doesn’t execute. Here is a
code snippet that demonstrate the same:

....
try {
//try block
[Link]("Inside try block");
[Link](0)
}
catch (Exception exp) {
[Link](exp);
}
finally {
[Link]("Java finally block");
}
....

In the above example if the [Link](0) gets called without any exception then finally won’t
execute. However if any exception occurs while calling [Link](0) then finally block will be
executed.

try-catch-finally block
 Either a try statement should be associated with a catch block or with finally.
 Since catch performs exception handling and finally performs the cleanup, the best
approach is to use both of them.

Syntax:

try {
//statements that may cause an exception
}
catch (…) {
//error handling code
}
finally {
//statements to be executed
}

Examples of Try catch finally blocks

Example 1: The following example demonstrate the working of finally block when no exception
occurs in try block

class Example1{
public static void main(String args[]){
try{
[Link]("First statement of try block");
int num=45/3;
[Link](num);
}
catch(ArrayIndexOutOfBoundsException e){
[Link]("ArrayIndexOutOfBoundsException");
}
finally{
[Link]("finally block");
}
[Link]("Out of try-catch-finally block");
}
}

Output:

First statement of try block


15
finally block
Out of try-catch-finally block

Example 2: This example shows the working of finally block when an exception occurs in try
block but is not handled in the catch block:

class Example2{
public static void main(String args[]){
try{
[Link]("First statement of try block");
int num=45/0;
[Link](num);
}
catch(ArrayIndexOutOfBoundsException e){
[Link]("ArrayIndexOutOfBoundsException");
}
finally{
[Link]("finally block");
}
[Link]("Out of try-catch-finally block");
}
}

Output:

First statement of try block


finally block
Exception in thread "main" [Link]: / by zero
at [Link]([Link])

As you can see that the system generated exception message is shown but before that the finally
block successfully executed.

Example 3: When exception occurs in try block and handled properly in catch block
class Example3{
public static void main(String args[]){
try{
[Link]("First statement of try block");
int num=45/0;
[Link](num);
}
catch(ArithmeticException e){
[Link]("ArithmeticException");
}
finally{
[Link]("finally block");
}
[Link]("Out of try-catch-finally block");
}
}

Output:

First statement of try block


ArithmeticException
finally block
Out of try-catch-finally block

Common questions

Powered by AI

Nested try-catch blocks interact with finally in that each try block can have its own associated finally block which will execute after the try and any pertinent catch blocks. The outer finally block will run after the completion of the inner try-catch-finally sequence when placed accordingly. This ensures that even with multiple layers of exception handling, all critical finalization code executes regardless of how deep the exception was handled .

When System.exit() is called within a try block, it disrupts the normal control flow entirely by terminating the program, hence preventing the finally block from executing. This behavior contrasts with methods like return, which allow the finally block to run before returning. The direct end to program execution that System.exit() causes underscores the need for caution when using it in try blocks, especially when critical operations are placed in finally blocks .

If an exception occurs within a finally block, it can obscure exceptions that might have occurred in the try block, since exceptions in finally can halt its execution as well. This could disrupt the intended cleanup process and may lead to resource leaks if not properly handled. It highlights the critical need for robust error handling within finally blocks themselves or using nested try-catch within finally to handle possible exceptions .

Placing statements that must always be executed, such as resource deallocation or closing connections, in the finally block ensures they run irrespective of whether an exception occurs. While the try block may throw exceptions preventing further execution, and the catch block may only run if exceptions of specific types occur, the finally block’s execution is almost guaranteed unless interrupted by methods like System.exit().

The finally block in Java exception handling is designed to execute important statements that must run regardless of whether an exception occurs in the try block or not. It is used to ensure resource clean-up, such as closing connections or streams, crucial for maintaining application stability. When exceptions occur in the try block, the finally block still executes after the catch block, if present, or directly after the try block if no catch block is used .

The finally block in Java does not execute if the System.exit() method is called in the try block, or if the Thread is terminated abruptly, or if an exception is thrown in the finally block itself before other statements in finally can execute. This deviates from its normal behavior where the finally block is expected to execute regardless of the flow in the try-catch construct .

The close() method should be used inside the finally block to ensure that all input and output streams are closed properly, thus releasing resources regardless of whether an exception is thrown or not. Given that the finally block executes even when exceptions occur, placing the close() method in finally provides a reliable mechanism to always clean up resources used in the try block .

The try-catch-finally block provides both error handling and cleanup, with catch handling specific exceptions thrown by the try block. In try-finally, catch is omitted, so the block is used simply to ensure that the finally executes, often for cleanup when specific exception handling is not required. Try-catch-finally offers a more comprehensive handling by addressing both immediate exception handling and guaranteeing resource cleanup .

In a scenario where a try block is followed by catch and finally blocks, if no exceptions occur within the try block, the statements in the try block execute normally, followed by the finally block, bypassing the catch block. For instance, consider the code that divides two numbers without exceptions: try prints statements, skips catch since no exception is raised, and finally executes its statements for cleanup .

When a return statement is executed in the try block, the finally block still executes before the method returns control to the calling method. This characteristic allows the finally block to execute cleanup operations even if a return statement is encountered, ensuring that critical operations are not bypassed when exiting the method prematurely .

You might also like