They differ if

  • the try-block completes by throwing a java.lang.Throwable that is not a java.lang.Exception, for instance because it is a java.lang.Error such as AssertionError or OutOfMemoryError.
  • the try-block completes abruptly using a control flow statement such a continue, break or return
  • the catch-block completes abruptly (by throwing any throwable, or using a control flow statement)

More generally, the java language guarantees that a finally block is executed before the try-statement completes. (Note that if the try-statement does not complete, there is no guarantee about the finally. A statement might not complete for a variety of reasons, including hardware shutdown, OS shutdown, VM shutdown (for instance due to System.exit), the thread waiting (Thread.suspend(), synchronized, Object.wait(), Thread.sleep()) or being otherwise busy (endless loops, ,,,).

So, a finally block is a better place for clean-up actions than the end of the method body, but in itself, still can not guarantee cleanup exeuction.

Answer from meriton on Stack Overflow
๐ŸŒ
W3Schools
w3schools.com โ€บ java โ€บ ref_keyword_finally.asp
Java finally Keyword
HTML CSS JAVASCRIPT SQL PYTHON ... SCIENCE INTRO TO PROGRAMMING BASH RUST ... Variables Print Variables Multiple Variables Identifiers Constants (Final) Real-Life Examples Java Data Types ยท Data Types Numbers Booleans Characters Real-Life Example Non-primitive Types The var Keyword Java Type ...
๐ŸŒ
DataCamp
datacamp.com โ€บ doc โ€บ java โ€บ finally
finally Keyword in Java: Usage & Examples
Learn how to use the `finally` block in Java for effective exception handling and resource management. Ensure your cleanup code always runs, regardless of exceptions. Examples and best practices included.
People also ask

What is the purpose of the 'finally' block in Java exception handling?
The 'finally' block in Java exception handling is used to execute important code such as resource cleanup, irrespective of whether an exception is thrown or not. It always runs after the try-catch block, ensuring that necessary operations like closing files or releasing resources occur even if an error happens.
๐ŸŒ
studysmarter.co.uk
studysmarter.co.uk โ€บ java finally
Java Finally: Definition, Keyword & Example | StudySmarter
When is the 'finally' block executed in a Java program?
The 'finally' block in a Java program is executed after the try-catch blocks, regardless of whether an exception is thrown or caught. It runs even if the try block completes successfully or an exception occurs. It won't execute if the JVM exits due to a call to System.exit() or if it's terminated abruptly.
๐ŸŒ
studysmarter.co.uk
studysmarter.co.uk โ€บ java finally
Java Finally: Definition, Keyword & Example | StudySmarter
Can a 'finally' block modify the return value of a method in Java?
Yes, a 'finally' block can modify the return value of a method in Java by altering the value of a non-final variable declared outside the try-catch-finally block, which is used as a return value. However, if the return statement occurs before entering the finally block, changes in finally won't affect the already returned value.
๐ŸŒ
studysmarter.co.uk
studysmarter.co.uk โ€บ java finally
Java Finally: Definition, Keyword & Example | StudySmarter
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ java โ€บ java-final-finally-and-finalize
Java final, finally and finalize - GeeksforGeeks
January 6, 2016 - In Java, the keywords "final", "finally" and "finalize" have distinct roles. final enforces immutability and prevents changes to variables, methods or classes. finally ensures a block of code runs after a try-catch, regardless of exceptions.
๐ŸŒ
Baeldung
baeldung.com โ€บ home โ€บ java โ€บ core java โ€บ guide to the java finally keyword
Guide to the Java finally Keyword | Baeldung
January 16, 2024 - Weโ€™ll also discuss some common pitfalls where a finally block can have an unexpected outcome. finally defines a block of code we use along with the try keyword. It defines code thatโ€™s always run after the try and any catch block, before ...
๐ŸŒ
Oracle
docs.oracle.com โ€บ javase โ€บ tutorial โ€บ essential โ€บ exceptions โ€บ finally.html
The finally Block (The Javaโ„ข Tutorials > Essential Java Classes > Exceptions)
See Java Language Changes for a summary of updated language features in Java SE 9 and subsequent releases. See JDK Release Notes for information about new features, enhancements, and removed or deprecated options for all JDK releases. The finally block always executes when the try block exits.
๐ŸŒ
Tutorialspoint
tutorialspoint.com โ€บ java โ€บ finally_keyword_in_java.htm
Finally Keyword in Java
Java finally keyword is used to define a finally block in a Java program. The finally block in Java follows a try block or a catch block.
๐ŸŒ
Unstop
unstop.com โ€บ home โ€บ blog โ€บ final, finally & finalize in java | 15+ differences (+codes)
Final, Finally & Finalize In Java | 15+ Differences (+Codes) // Unstop
November 15, 2024 - In Java, understanding the differences ... their similar names. The final keyword is used primarily for constant values, preventing inheritance, and prohibiting method overriding....
Find elsewhere
Top answer
1 of 10
47

They differ if

  • the try-block completes by throwing a java.lang.Throwable that is not a java.lang.Exception, for instance because it is a java.lang.Error such as AssertionError or OutOfMemoryError.
  • the try-block completes abruptly using a control flow statement such a continue, break or return
  • the catch-block completes abruptly (by throwing any throwable, or using a control flow statement)

More generally, the java language guarantees that a finally block is executed before the try-statement completes. (Note that if the try-statement does not complete, there is no guarantee about the finally. A statement might not complete for a variety of reasons, including hardware shutdown, OS shutdown, VM shutdown (for instance due to System.exit), the thread waiting (Thread.suspend(), synchronized, Object.wait(), Thread.sleep()) or being otherwise busy (endless loops, ,,,).

So, a finally block is a better place for clean-up actions than the end of the method body, but in itself, still can not guarantee cleanup exeuction.

2 of 10
32

finally block executes always.

finally block is used for cleanup, like to free resources used within try/catch, close db connections, close sockets, etc.. even when an unhandled exception occurs within your try/catch block.

The only time the finally block doesn't execute is whensystem.exit() is called in try/catch or some error occurs instead of an exception.

The error in the description above means when Java application exit with conditions like Out Of Memory error. I see some downvotes :( for this reason it seems.

๐ŸŒ
PREP INSTA
prepinsta.com โ€บ home โ€บ java tutorial โ€บ finally() keyword in java
Finally() Keyword in Java | PrepInsta
February 10, 2023 - Finally, a block in Java which always gets executed in the compiler whether an exception is handled or not. So it contains all the necessary statements that needs to be printed when a program gets executed, regardless of whether an exception ...
๐ŸŒ
StudySmarter
studysmarter.co.uk โ€บ java finally
Java Finally: Definition, Keyword & Example | StudySmarter
The 'finally' block in Java always gets executed except for in situations of abrupt termination of the JVM (Java Virtual Machine). ... The 'final' keyword in Java signifies immutability, restricting further modification of variables, methods, and classes.
๐ŸŒ
Medium
medium.com โ€บ @sharma0purnima โ€บ understanding-final-finally-and-finalize-in-java-29b19eb17519
Understanding final, finally, and finalize() in Java | by Purnima Sharma | Medium
July 13, 2024 - Understanding the differences between final, finally, and finalize() is crucial for writing robust and maintainable Java code. The final keyword ensures immutability, the finally block guarantees resource cleanup, and the finalize() method provides ...
๐ŸŒ
Scientech Easy
scientecheasy.com โ€บ home โ€บ blog โ€บ finally block in java | finally keyword in java
Finally Block in Java | Finally Keyword in Java - Scientech Easy
May 9, 2025 - A โ€œfinallyโ€ in Java is a keyword used to create a block of code that follows a try or catch block. A finally block contains all the crucial codes such as closing connections, stream, etc.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ java โ€บ final-keyword-in-java
final Keyword in Java - GeeksforGeeks
The final keyword is a non-access modifier used to restrict modification. It applies to variables (value cannot change) methods (cannot be overridden) and classes (cannot be extended).
Published ย  July 22, 2014
๐ŸŒ
DataCamp
datacamp.com โ€บ doc โ€บ java โ€บ final
final Keyword in Java: Usage & Examples
Java keywordsIntroduction To JavaJava File HandlingJava Language BasicsJava ArraysJava Object-Oriented Programming ... The final keyword in Java is a non-access modifier that can be applied to variables, methods, and classes. It is used to restrict the user from further modifying the entity ...
๐ŸŒ
YouTube
youtube.com โ€บ watch
Java Finally Keyword - Try Catch Finally Java Tutorial #47 - YouTube
$1,500 OFF ANY Springboard Tech Bootcamps with my code ALEXLEE1500. See if you qualify for the JOB GUARANTEE! ๐Ÿ‘‰ https://bit.ly/3HX970hThe finally keyword in...
Published ย  March 19, 2020
๐ŸŒ
Medium
medium.com โ€บ @AlexanderObregon โ€บ understanding-final-finally-and-finalize-in-java-c220bba0927e
Understanding Final, Finally, and Finalize in Java
March 18, 2025 - Java has three similar-looking keywords โ€” final, finally, and finalizeโ€”but they serve completely different purposes. While final deals with immutability and inheritance, finally is part of exception handling, and finalize was historically ...
๐ŸŒ
Medium
medium.com โ€บ @kimenjudenis_4641 โ€บ finally-keyword-in-java-dbc34896039d
finally Keyword in Java. Overview | by DenisTheDev | Medium
November 23, 2023 - public class FinallyClass{ public static void finallyMethod() { int num1 = 1; int num2 = 0; try { int result = num1/num2; } catch(ArithmeticException e) { e.printStackTrace(); System.out.println("In catch block"); } finally { System.out.println("In finally block"); } } public static void main(String[]args) { finallyMethod(); } } ... java.lang.ArithmeticException: / by zero at Tests.A.finallyMethod(A.java:9) at Tests.A.main(A.java:21) In catch block In finally block
๐ŸŒ
Javatpoint
javatpoint.com โ€บ finally-block-in-exception-handling
Java Finally block - javatpoint
Java finally block is a block that is always executed. Let's see its application and example.
Top answer
1 of 2
30

Short Answer

Finally blocks are guaranteed to run no matter what happens inside of the try and catch blocks, before allowing the program to crash.

This is sort of explained here: https://www.php.net/manual/en/language.exceptions.php though the explanation isn't particularly detailed.

Some More Detail

One example that comes to the top of my head is if you are dealing with input/output streams or something similar that has to be closed after use in order to avoid a memory leak. To use your example:

try {
  memoryUser.startReading(someFileOrSomething);
}
catch (CustomException $customException) {
  // handle custom error
}
catch (Exception $exception) {
  // handle the error
  invisibleBug.whoops(); // i.e. something goes wrong in this block
}

memoryUser.Close(); // because something went wrong in the catch block,
                    // this never runs, which, in this case, causes a memory leak

In this case, wrapping the memoryUser.Close(); in a finally block would ensure that that line would run before the rest of the program exploded, preventing the memory leak even in an otherwise catastrophic failure.

TL;DR

So a lot of the time, people put the finally block there to ensure an important line runs, even if they overlooked something in the catch blocks. This is how I've always seen it used.

Hopefully this helps :)

2 of 2
27

What's special about a finally {} block is that it will always run at the end of the try {} block.

  • It will run if the code in the try {} block completes successfully.

  • It will run if the code in the try {} block throws an exception that was caught by a catch {}. (The finally {} runs after the catch {}.)

  • It will run if the code in the try {} block throws an exception that wasn't handled by any catch {} block, or if there weren't any at all. (The finally {} block runs before the exception is propagated to the caller.)

  • It will run if the code in the try {} block throws an exception, and the code in the catch {} throws another exception (or rethrows the same exception).

  • It will even run if the code in the try {} block, or in a catch {} block, uses return. (Just as with an uncaught exception, the finally {} runs before the function actually returns.) The finally {} block can even use return itself, and its return value will override the value that the other block tried to return!

(There is one edge case where a finally {} block won't run, and that's if the entire process is destroyed, e.g. by being killed, or by calling exit() or die().)