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 OverflowThis 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();
}
}
It's there because the programmer wanted to make sure that db.cleanup() is called even if the code inside the try block throws an exception. Any exceptions will not be handled by that block, but they'll only be propagated upwards after the finally block is executed. The finally block will also be executed if there was no exception.
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.
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.
Is there a "try" without "catch" in Javascript?
Using `try`/`finally` without `catch` - Question - Scala Users
exceptions - Is the 'finally' portion of a 'try ... catch ... finally' construct/structure even necessary? - Software Engineering Stack Exchange
Need help solving 'try' without 'catch', 'finally' or resource declarations error.
Videos
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();
}
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+
I want to try action A, and if it fails try action B, and if it fails, try action C. I need to do that without having to specify a "catch". Is that possible? Thanks!
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.
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;.
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
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.
finally should have atleast a try block, catch is optional. The point of finally blocks is to make sure stuff gets cleaned up whether an exception is thrown or not. As per the JLS
A finally clause ensures that the finally block is executed after the try block and any catch block that might be executed, no matter how control leaves the try block or catch block.
Hence a finally should always be preceded by a try block.
You must have a try block with a finally block. The try block defines which lines of code will be followed by the finally code. If an exception is thrown prior to the try block, the finally code will not execute.
Adding catch blocks is optional:
try {
// something
} finally {
// guaranteed to run if execution enters the try block
}