This is useful if you want the currently executing method to still throw the exception while allowing resources to be cleaned up appropriately. Below is a concrete example of handling the exception from a calling method.

public void yourOtherMethod() {
    try {
        yourMethod();
    } catch (YourException ex) {
        // handle exception
    }
}    

public void yourMethod() throws YourException {
    try {
        db.store(mydata);
    } finally {
        db.cleanup();
    }
}
Answer from Taylor Leese on Stack Overflow
Top answer
1 of 9
182

It depends on whether you can deal with the exceptions that can be raised at this point or not.

If you can handle the exceptions locally you should, and it is better to handle the error as close to where it is raised as possible.

If you can't handle them locally then just having a try / finally block is perfectly reasonable - assuming there's some code you need to execute regardless of whether the method succeeded or not. For example (from Neil's comment), opening a stream and then passing that stream to an inner method to be loaded is an excellent example of when you'd need try { } finally { }, using the finally clause to ensure that the stream is closed regardless of the success or failure of the read.

However, you will still need an exception handler somewhere in your code - unless you want your application to crash completely of course. It depends on the architecture of your application exactly where that handler is.

2 of 9
40

The finally block is used for code that must always run, whether an error condition (exception) occurred or not.

The code in the finally block is run after the try block completes and, if a caught exception occurred, after the corresponding catch block completes. It is always run, even if an uncaught exception occurred in the try or catch block.

The finally block is typically used for closing files, network connections, etc. that were opened in the try block. The reason is that the file or network connection must be closed, whether the operation using that file or network connection succeeded or whether it failed.

Care should be taken in the finally block to ensure that it does not itself throw an exception. For example, be doubly sure to check all variables for null, etc.

Discussions

Is there a "try" without "catch" in Javascript?
In JavaScript, the try block must be accompanied with either a catch block or finally block. From ES2019 and onward, you can have an empty catch block. It sounds like you want to have nested try-catch blocks to execute backup plans. Can you share details of the scope of your program? My gut is telling me there is most likely a cleaner way of implementing your functionality without nested try-catch blocks. More on reddit.com
🌐 r/learnjavascript
33
26
April 29, 2024
Using `try`/`finally` without `catch` - Question - Scala Users
If I need to compute something but do some side effect before returning that value, is the correct idiom try/finally without catch ? e.g., def calculateSemesterAverage() = { import scala.io.Source def csv = Source.fromFile("some-file-to-parse.csv") try { for {line More on users.scala-lang.org
🌐 users.scala-lang.org
0
June 22, 2020
exceptions - Is the 'finally' portion of a 'try ... catch ... finally' construct/structure even necessary? - Software Engineering Stack Exchange
Some languages (such as C++ and early versions of PHP) don't support the finally part of a try ... catch ... finally construct. Is finally ever necessary? Because the code in it always runs, why wouldn't/shouldn't I just place that code after a try ... catch block without a finally clause? More on softwareengineering.stackexchange.com
🌐 softwareengineering.stackexchange.com
January 26, 2015
Need help solving 'try' without 'catch', 'finally' or resource declarations error.
OK, it took me a bit to unravel your code because either you've done a great job of obfuscating your own indentation, or codepen absolutely demolished it. So the issue is where you've done try {/ serverSocket = new ServerSocket(1098,500); This try block exists, but it has no catch or finally. Try blocks always have to do one of three things, catch an exception, terminate with a finally (This is generally to close resources like database connections, or run some code that NEEDS to be executed regardless of if an error occurs), or be a try-with-resources block (This is the Java 7+ way of closing resources, like file readers). This block currently doesn't do any of those things. So I would question then is it actually a needed try block? If so, you need to complete it. If not, you need to remove it. More on reddit.com
🌐 r/javahelp
3
3
May 5, 2022
Top answer
1 of 10
193

You would use it to ensure some actions occur after the try content or on an exception, but when you don't wish to consume that exception.

Just to be clear, this doesn't hide exceptions. The finally block is run before the exception is propagated up the call stack.

You would also inadvertently use it when you use the using keyword, because this compiles into a try-finally (not an exact conversion, but for argument's sake it is close enough).

try
{
    TrySomeCodeThatMightException();
}
finally
{
    CleanupEvenOnFailure();
}

Code running in finally is not guaranteed to run, however the case where it isn't guaranteed is fairly edge - I can't even remember it. All I remember is, if you are in that case, chances are very good that not running the finally isn't your biggest problem :-) so basically don't sweat it.

Update from Tobias: finally will not run if the process is killed.

Update from Paddy: Conditions when finally does not execute in a .net try..finally block

The most prevalent example you may see is disposing of a database connection or external resource even if the code fails:

using (var conn = new SqlConnection("")) // Ignore the fact we likely use ORM ;-)
{
    // Do stuff.
}

Compiles into something like:

SqlConnection conn;

try
{
    conn = new SqlConnection("");
    // Do stuff.
}
finally
{
    if (conn != null)
        conn.Dispose();
}
2 of 10
12

Good Explaination using code:

void MyMethod1()
{
    try
    {
        MyMethod2();
        MyMethod3();
    }
    catch(Exception e)
    {
        //do something with the exception
    }
}


void MyMethod2()
{
    try
    {
        //perform actions that need cleaning up
    }
    finally
    {
        //clean up
    }
}


void MyMethod3()
{
    //do something
}

If either MyMethod2 or MyMethod3 throws an exception, it will be caught by MyMethod1. However, the code in MyMethod2 needs to run clean up code, e.g. closing a database connection, before the exception is passed to MyMethod1.

http://forums.asp.net/t/1092267.aspx?Try+without+Catch+but+with+finally+doesn+t+throw+error+Why+no+syntax+error+

🌐
Scala Users
users.scala-lang.org › question
Using `try`/`finally` without `catch` - Question - Scala Users
June 22, 2020 - If I need to compute something but do some side effect before returning that value, is the correct idiom try/finally without catch ? e.g., def calculateSemesterAverage() = { import scala.io.Source def csv = Source.fromFile("some-file-to-parse.csv") try { for {line
🌐
Microsoft Learn
learn.microsoft.com › en-us › dotnet › csharp › language-reference › statements › exception-handling-statements
Exception-handling statements - throw and try, catch, finally - C# reference | Microsoft Learn
You can use the try statement in any of the following forms: try-catch - to handle exceptions that might occur during execution of the code inside a try block, try-finally - to specify the code that runs when control leaves the try block, and ...
🌐
PHP
php.net › manual › en › language.exceptions.php
PHP: Exceptions - Manual
If an exception is thrown and its current function scope has no catch block, the exception will "bubble up" the call stack to the calling function until it finds a matching catch block.
Find elsewhere
🌐
Esdiscuss
esdiscuss.org › topic › try-without-catch-or-finally
try without catch or finally
The lack of parentheses make it clear that the word following 'except' is not the error parameter, and the lack of braces clearly means the catch-phrase ends at the semicolon. It could even be immediately followed by a finally, which I think yields some terse, but useful syntax that's intuitive and consistent. ... Why is the argument and curly brace syntax required for except? Why not simply allow: try { throw ExceptionalException; } catch dosubroutine(); which for the convenience of Jussi's original ask: try { //fail } catch null; (or if you prefer, a noop call).
Top answer
1 of 12
41

In addition to what others have said, it's also possible for an exception to be thrown inside the catch clause. Consider this:

try { 
    throw new SomeException();
} catch {
    DoSomethingWhichUnexpectedlyThrows();
}
Cleanup();

In this example, the Cleanup() function never runs, because an exception gets thrown in the catch clause and the next highest up catch in the call stack will catch that. Using a finally block removes this risk, and makes the code cleaner to boot.

2 of 12
60

As others have mentioned, there's no guarantee that code after a try statement will execute unless you catch every possible exception. That said, this:

try {
   mightThrowSpecificException();
} catch (SpecificException e) {
   handleError();
} finally {
   cleanUp();
}

can be rewritten1 as:

try {
   mightThrowSpecificException();
} catch (SpecificException e) {
   try {
       handleError();
   } catch (Throwable e2) {
       cleanUp();
       throw e2;
   }
} catch (Throwable e) {
   cleanUp();
   throw e;
}
cleanUp();

But the latter requires you to catch all unhandled exceptions, duplicate the cleanup code, and remember to re-throw. So finally isn't necessary, but it's useful.

C++ doesn't have finally because Bjarne Stroustrup believes RAII is better, or at least suffices for most cases:

Why doesn't C++ provide a "finally" construct?

Because C++ supports an alternative that is almost always better: The "resource acquisition is initialization" technique (TC++PL3 section 14.4). The basic idea is to represent a resource by a local object, so that the local object's destructor will release the resource. That way, the programmer cannot forget to release the resource.


1 The specific code to catch all exceptions and rethrow without losing stack trace information varies by language. I have used Java, where the stack trace is captured when the exception is created. In C# you'd just use throw;.

🌐
Medium
medium.com › @AlexanderObregon › how-javas-try-finally-blocks-work-without-catch-96e93be92ae5
How Java’s try-finally Blocks Work Without catch | Medium
March 4, 2025 - The inner finally block runs first before the program exits the inner try-finally, and then the outer finally block runs before the exception leaves main(). The finally block in Java is often used to handle cleanup tasks that must happen regardless of how a method exits. These tasks include closing files, releasing memory, and shutting down connections. Since finally always executes, it provides a structured way to handle these operations without requiring a catch block.
🌐
Reddit
reddit.com › r/javahelp › need help solving 'try' without 'catch', 'finally' or resource declarations error.
r/javahelp on Reddit: Need help solving 'try' without 'catch', 'finally' or resource declarations error.
May 5, 2022 -

I keep receiving this error: 'try' without 'catch', 'finally' or resource declarations. I’ve tried to add and remove curly brackets, add final blocks, and catch blocks and nothing is working.

https://codepen.io/angelineb/pen/KKQpbqV

Top answer
1 of 3
2
OK, it took me a bit to unravel your code because either you've done a great job of obfuscating your own indentation, or codepen absolutely demolished it. So the issue is where you've done try {/ serverSocket = new ServerSocket(1098,500); This try block exists, but it has no catch or finally. Try blocks always have to do one of three things, catch an exception, terminate with a finally (This is generally to close resources like database connections, or run some code that NEEDS to be executed regardless of if an error occurs), or be a try-with-resources block (This is the Java 7+ way of closing resources, like file readers). This block currently doesn't do any of those things. So I would question then is it actually a needed try block? If so, you need to complete it. If not, you need to remove it.
2 of 3
1
Please ensure that: Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions You include any and all error messages in full You ask clear questions You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions. Trying to solve problems on your own is a very important skill. Also, see Learn to help yourself in the sidebar If any of the above points is not met, your post can and will be removed without further warning. Code is to be formatted as code block (old reddit: empty line before the code, each code line indented by 4 spaces, new reddit: https://imgur.com/a/fgoFFis ) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc. Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit. Code blocks look like this: public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } } You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above. If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures. To potential helpers Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.
🌐
Tutorialspoint
tutorialspoint.com › java › java_finally_block.htm
Java - Finally Block
It is not compulsory to have finally clauses whenever a try/catch block is present. The try block cannot be present without either catch clause or finally clause.
🌐
Java2Blog
java2blog.com › home › core java › exception handling › can we have try without catch block in java
Can We Have Try without Catch Block in Java - Java2Blog
February 19, 2024 - In Java, it’s possible to use a try block without a catch block, but it must be followed either by a finally block or be part of a try-with-resources statement. ... You can use a try block with a finally block. As you may know, the finally block always executes, even if there is an exception ...
🌐
Cppreference
en.cppreference.com › w › cpp › language › try_catch.html
cpp/language/try catch - cppreference.com
June 6, 2024 - cppreference.com · Create account · Log in · Namespaces · Discussion · Variants · Views · History · Actions · cpp/language/try catch
🌐
Reddit
reddit.com › r/csharp › regarding try/catch block's finally keyword in c#
r/csharp on Reddit: Regarding try/catch block's finally keyword in C#
May 12, 2024 -

Okay, so I am very familiar with try and except (or catch in c# I guess), but the one I am not sure about is the finally keyword used like:

finally

{

Console.WriteLine("This worked anyway");

}

I understand that this is supposed to run regardless if the Try or Except worked, but the question I have (and also sort of the problem I have with this) is whatever you are doing in this, couldn't you also just do outside of the try/catch block of code? I'm not entirely sure why this is necessary in C# (or in any language). Can someone please explain why we need this.

🌐
Oracle
docs.oracle.com › javase › tutorial › essential › exceptions › finally.html
The finally Block (The Java™ Tutorials > Essential Java Classes > Exceptions)
But finally is useful for more ... or break. Putting cleanup code in a finally block is always a good practice, even when no exceptions are anticipated. Note: The finally block may not execute if the JVM exits while the try or catch code is being executed....
🌐
Dotnet Tutorial
dotnetustad.com › c-sharp › try-block-without-catch-block
Can we have only try block without catch block?
Indeed, it's possible to use a try block without pairing it with a catch block. Often this approach is taken when executing code that may trigger an exception, yet there's no requirement to immediately address this exception within that segment ...
🌐
Object Computing
objectcomputing.com › resources › publications › sett › may-2000-an-integral-part-of-exception-handling-finally
An Integral Part of Exception Handling, Finally | Object Computing, Inc.
This article focuses on the technical details of the finally block, and situations where it can be put to good use. Note: The try-catch paradigm exists in C++, but that language does not support finally.
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Statements › try...catch
try...catch - JavaScript - MDN Web Docs - Mozilla
March 9, 2026 - If any statement within the try block (or in a function called from within the try block) throws an exception, control is immediately shifted to the catch block. If no exception is thrown in the try block, the catch block is skipped. The finally block will always execute before control flow ...