Is finally block in C# a must? - c#

What is the difference between 2 conditions? Every time when method1 or method2 runs, there should be a code block that is required to run. It seems to me that 2 method are the same.
// example method1
void Method1(void)
{
try
{
// do something
}
catch (Exception ex)
{
// do something
}
finally
{
// do something whenever method1 runs
}
}
// example method2
void Method2(void)
{
try
{
// do something
}
catch (Exception ex)
{
// do something
}
// do something whenever method2 runs
}
Finally block seems to be unnecessary for me.

In your first example, you could re-throw the exception and the code inside the finally would still run. This would not be possible in the second example.
If you choose not to re-throw the exception, then yes there is little difference. However, this is considered bad form - very rarely should you need to consume an exception that you cannot explicitly handle.
It is a keyword to help you with code execution flow. When you throw an exception the execution flow of the code is affected (like using return), the finally keyword allows you to express that when an exception occurs (or you return from a try) you still want execution to do something as it's leaving.
To answer the question facetiously, it is a must when you need it and not when you don't.
Further Reading
To be on the safe side, before you attempt to start making use of this keyword, please read the documentation for it:
http://msdn.microsoft.com/en-us/library/zwc8s4fz.aspx
And the exception handling keywords in general:
http://msdn.microsoft.com/en-us/library/s7fekhdy.aspx
Examples
Catch an exception to do something with it, then re-throw it. Use finally to call any tidy-up code:
try
{
OpenConnectionToDatabase();
// something likely to fail
}
catch (Exception ex)
{
Log(ex);
throw;
// throw ex; // also works but behaves differently
}
// Not specifying an exception parameter also works, but you don't get exception details.
//catch (Exception)
//{
// Log("Something went wrong);
// throw;
//}
finally
{
CloseConnectionToDatabase();
}
Don't register any interest in catching exceptions, but use finally to tidy-up code:
try
{
OpenConnectionToDatabase();
// something likely to fail
}
finally
{
CloseConnectionToDatabase();
}
Return from your try because it looks nicely formatted, but still use finally to tidy-up code:
try
{
OpenConnectionToDatabase();
return 42;
}
finally
{
CloseConnectionToDatabase();
}

As you know the code written inside the finally block always runs.
Please have a look onto the following point written below, it will clear your all confusion.
Finally is used for Resource management. Mainly for releasing an resources. It always runs independent upon the Exception.
As we know catch is used for handle an exception, but sometimes it fails to handle to an External exception. Then the finally block is used to handle that exception to perform the operation.

The code in the finally block will run anyway after the try-catch, it is very usefull for clean up.
try
{
// open resources
}
catch (Exception ex)
{
// something bad happened
}
finally
{
// close resources that are still opened
}

This will behave very differently depending on whether you return from the try, for example. Also - the finally will run even if the catch throws an exception (or re-throws the original exception), which will not happen without the finally.
So: it isn't required, but it will behave differently. So if you want the code to happen, put it in the finally.
In many ways, try/finally is much more common than try/catch or try/catch/finally.

You do not absolutely have to have the finally block, however, having it guarantees that the code within it will always run (unless there is an exception in the finally!).
Consider the following:
void Method2(void)
{
try
{
// do something
}
catch (Exception ex)
{
// do something
throw;
}
// do something whenever method2 runs
}
the code after the try/catch will not execute if an exception is thrown. Additionally, if the code within the catch block has an error that causes an exception (such as your logging throwing an unexpected exception) the code that should have been in the finally will not run, leaving and cleanup undone.
Also a return statement will cause that code to not be run, while the finally will still be executed (also, here you can see that the catch can be skipped too, allowing any exceptions to propogate upwards - AFTER executing the finally):
void Method2(void)
{
try
{
// do something
return
}
finally
{
// do something whenever method2 runs
}
}
Whenever you have cleanup code that must be run at the end of a method, use finally (or if your objects implement IDisposable use the using statement).

The finally block ensures that any code within it ALWAYS gets executed so if you have a return statement inside your try block or rethrow an exception within your catch block, the code inside the finally block will always execute.
It is a must if you need to ensure that something happens regardless (e.g. disposing of a resource etc)

The big difference is that try...catch will swallow the exception, hiding the fact that an error occurred. try..finally will run your cleanup code and then the exception will keep going, to be handled by something that knows what to do with it.

Related

Exception Handling within Exception Handling

What is the best practice for exception handling within exception handling?
I find myself working on an existing C# (Framework 4.0) system that uses custom objects within the catch and finally blocks throughout most of the Application Server tier of the system.
Consider the following snipped version of a method in this codebase:
public void DoSomeStuff(string sGUID)
{
try
{
// Foo
}
catch (Exception oEx)
{
oExceptions.Add(oEx);
if (oDBConn.NumberOfActiveTrans > 0)
{
oDBConn.Rollback();
}
}
finally
{
oDBConn.DeleteLocksByGUID(sGUID);
}
}
I might be being overly paranoid, but I find myself very worried about possible unhandled exceptions that may occur with these.
As such, would something like the following updated version be an acceptable practice or is there a better way to accomplish the same thing?
public void DoSomeStuff(string sGUID)
{
try
{
// Foo
}
catch (Exception oEx)
{
oExceptions.Add(oEx);
try
{
if (oDBConn.NumberOfActiveTrans > 0)
{
oDBConn.Rollback();
}
}
catch (Exception oEEx)
{
oExceptions.Add(oEEx);
}
}
finally
{
try
{
oDBConn.DeleteLocksByGUID(sGUID);
}
catch (Exception oFEx)
{
oExceptions.Add(oFEx);
}
}
}
I personally wouldn't add a try catch block in the finally, then it can be an endless chain. Usually you shouldn't have complicated stuff in the finally and in any case unexpected exception should be caught in the caller.
Edit: looking a bit closer to the code, I don't see why the code in the finally shouldn't be in the try block.
I might be being overly paranoid, but I find myself very worried about
possible unhandled exceptions that may occur with these.
Don't panic. If there is an error in the db layer try catch it there.
The most dangerous thing in the original code is that if it fails and the transaction rollback fails, the only error rethrown will be the one from rolling back the transaction. You'll never know what the original exception was that caused you to have to roll back the transaction. That's the one that you probably care most about.
If you want to be paranoid, log the failure of the transaction rollback. But what matters is the previous exception that got you to that point. That should either be logged or rethrown depending on the expectation of the caller.

What is the difference between try-finally and try-catch-throw?

So, I understand from this question that finally blocks can be used to execute code even if an Exception occurs and even if the Exception is uncaught and allowed to propagate up.
I understand from this question that in C#, the throw keyword can be used alone (with no arguments) in a catch block to allow the caught Exception to continue propagating up without even resetting the stack trace.
My question, then, is what is the difference between THESE two blocks:
/* example 1 */
try { /* try stuff */ }
finally { /* finally/catch stuff */ }
/* example 2 */
try { /* try stuff */ }
catch { /* finally/catch stuff */ throw; }
Don't both run the stuff the try stuff, then run the finally/catch stuff, then allow the thrown Exception to propogate up with the same stack trace?
In
try { /* try stuff */ }
catch { /* finally/catch stuff */ throw; }
the finally stuff won't run when there is no error.
A finally{} block is used for cleanup, your suggestion would litter valuable resources.
You really missed the point here, only catch is about handling errors (optionally in stages). A finally block is about resource management and only related to exceptions in the sense that it will execute despite of any exceptions having occurred.
Think of it like this...
try
{
//do some stuff
}
catch
{
//do some stuff if there was an exception
//maybe some cleanup, maybe rethrow exception
}
finally
{
//always do this stuff exception or not
}
catch runs only if content of try throws an error, finally runs always after try and/or catch.
The difference is that the finally block is always executed both if you have an exception or not, instead the catch block is executed only if you have an exception
A finally will run regardless as to whether your code throws an exception or not, but it is my understanding (i could be wrong) that it may not run if you re-throw in a catch which is in turn not handled. The finally is useful when you need to tidy up regardless of whether an error occurred or not, such as disposing connections.
The second example would only have code run in the catch, or if the code doesn't throw and exception. In which case I would remove the try catch and let it bubble up and have the try catch higher up

What is the finally block for compared to just writing code after the try statement?

In other words, how are these two different?
try
{
// Something that can throw an error
}
catch
{
// Handle the error
}
finally
{
// Something that runs after the try statement
}
vs.
try
{
// Something that can throw an error
}
catch
{
// Handle the error
}
// Something that runs after the try statement
finally block always executes.
You can be sure, that this block will be executed no matter what.
Literally it is something like:
Try something, catch some exceptions(if told to and if they are there) and execute the
finally block finally.
If there is a break in the try block or an exception, it may cause the program to halt. In cases like these code that is mandarory to be executed, like closing open connections and returning items to the connection pools are writen in the finally block. The finally block ensures that the code written inside it will be executed.
If you only ever use general catches (i.e. catch without args or catch(Exception ex)), whether to put code in finally or after try/catch is basically a stylistic choice, as both a finally block and code after a try/catch will execute in any situation (barring deliberate escape mechanisms such as return).
However, if you use a narrow catch, and the exception isn't caught, what will happen is the finally block will still execute, however the code after the try/catch won't.

What is the purpose of "finally" in try/catch/finally

The syntax will change from language to language, but this is a general question.
What is the difference between this....
try
{
Console.WriteLine("Executing the try statement.");
throw new NullReferenceException();
}
catch (NullReferenceException e)
{
Console.WriteLine("{0} Caught exception #1.", e);
}
finally
{
Console.WriteLine("Executing finally block.");
}
and this....
try
{
Console.WriteLine("Executing the try statement.");
throw new NullReferenceException();
}
catch (NullReferenceException e)
{
Console.WriteLine("{0} Caught exception #1.", e);
}
Console.WriteLine("Executing finally block.");
I keep seeing it being used, so I assume there's a good reason to use finally, but I can't figure out how it's any different from just putting code after the statement since it will still run.
Is there ever a scenario where finally doesn't run?
In your example, it doesn't make a whole lot of difference.
Picture this, though:
try
{
Console.WriteLine("Executing the try statement.");
throw new NullReferenceException();
}
catch (SomeOtherException e)
{
Console.WriteLine("{0} Caught exception #1.", e);
}
finally
{
Console.WriteLine("Executing finally block.");
}
Console.WriteLine("Executing stuff after try/catch/finally.");
In this case, the catch won't catch the error, so anything after the whole try/catch/finally will never be reached. However, the finally block will still run.
try
{
throw new Exception("Error!");
}
catch (Exception ex)
{
throw new Exception(ex, "Rethrowing!");
}
finally
{
// Will still run even through the catch kicked us out of the procedure
}
Console.WriteLine("Doesn't execute anymore because catch threw exception");
It really depends - some other answers have very good reasons to use a Finally block. But I think the best reason is because you're doing exception handling. Things you do in a Finally block typically involve cleaning up resources to ensure proper continuation, regardless of whether or not an exception was thrown - to me that's still part of the exception handling, at least part of a "try something" operation.
IMHO the Finally scope highlights the fact that its code contains stuff that deserves special attention in case of an exception.
finally block is guaranted to be excuted.
So, in your example, results of both cases are looks same.
but if you use return or throw in your catch block, you can see what is difference.
Finally should be used to everything that needs to be done in order to keep a system consistent. This usually means release resources
Finally is always executed, no matter what exception was thrown. It should be used to release resources, in the following cases:
Finalize a connection
Close a file handler
Free memory
Close a database connection
Let me give a complete example. Imagine that that you are sending messages through the network. In pseudo-code:
// With finally | //Without finally
try{ | try{
send_message() | send_message()
} catch(NetworkError){ | } catch(NetworkError){
deal_with_exception() | deal_with_exception()
} finally { | }
finalizes_connection() | finalizes_connection()
} |
The only difference of both codes is when what is hold in the try block raises an exception that is not NetworkError, for example, MethodNotFound. In the first case, the method finalizes_connection() will be called, and in the second one, it will not.
A connection is naturally done through more than one program. So what happens in the case of a MethodNotFound exception to the other program? In the first case, your program will finish the connection and the other program and it will be happy. In the second case, the other program can be waiting for your response forever. What if the other program can only receive one connection per time? You just bugged the other program as well.
This would also apply for a file, for example, that you opened and other programs wouldn't be able to open for reading (in Windows). And for memory, it is never released and now you have a memory leak.
finally runs for both try and catch. It ensures that it will run, but it is not 100% guaranteed it will [some errors stop execution of code]
try block needs at least one catch or a finally.after executing all catch blocks the finally block will be executed.You can add any logic you need there which should be done ultimately.
Its a good practice to use finally to handle program crashes. finally will always run .If the function exits inside of the try catch block, or another error is thrown in either the try or the catch, the finally will still execute. You won't get that functionality not using the finally statement.
I don't know C#, but the purpose of a finally block in Java-ish languages is to ensure that system resources are relinquished, especially if garbage collection is irregular. It's the same principle for all. Consider the block
InputStream is = new FileInputStream("foo.txt");
OutputStream os = new FileOutputStream("D:/nonexistent/directory/bar.txt");
// Throws a FileNotFoundException.
The variable is is created successfully, and takes up system resources. Processes can only use a fixed number of file handles at a time. The variable os is never created, and an exception is thrown, and bubbles up to the caller. In the process, is goes out of scope, and becomes eligible for garbage collection.
However garbage collections are never guaranteed to happen, or they may happen at some indefinite time in the future. So, the system resources taken by is may never be freed. This can be costly, or can crash the program if it happens enough times. So, finally blocks were put into Java. Other languages have similar constructs. In C++, destructors are invoked deterministically. LISPy languages have unwind-protect, but those are usually packaged in with-foo macros.
In Java 6 and lower, one would do this:
try {
is = new FileInputStream("foo.txt");
os = new FileOutputStream("D:/nonexistent/directory/bar.txt");
// work...
} finally {
if (is != null) {
try {
is.close();
} catch (IOException ignored) {}
}
if (os != null) {
try {
os.close();
} catch (IOException ignored) {}
}
}
You can't just call is.close() because that might throw, and then os will never be closed. You have to check for null too. Sane people used Jakarta Commons-IO's IOUtils.closeQuietly() methods to replace the block:
} finally {
IOUtils.closeQuietly(is);
IOUtils.closeQuietly(os);
}
But Java 7 introduced a better solution: try-with-resources. C# 4 probably came first with something similar, Microsoft being quicker on the uptake than Snoracle.
try (
is = new FileInputStream("foo.txt"),
os = new FileOutputStream("D:/nonexistent/directory/bar.txt")
) {
// work...
}
finally always always runs. finally is like the catcher that never misses anything. In the example you mentioned, yes finally doesnt add any value. But finally is usually used to dispose/ release resources.

C# - using return in catch clause

I saw a similar question here, but there are still some things I don't understand. As far as I know when you use try-catch block, if an exception is thrown the catch block will be executed right after and no code after the catch clause in the same code block will be executed. So if I get it right if we have:
try
{
// do something
// throw an exception for some reason
}
catch (Exceptiox ex)
{
// do something when there is and exception thrown
}
// some code that will never be runned if and exception was thrown above
I'm not 100% sure that the catch stops further execution outside its scope but this is one of my questions so correct me if I'm wrong.
So what's the point of using return in a catch block if you don't need to return any value at all? I see this in some methods from inherited code I'm working on. For example:
public void DeleteImage(AppConfig imageInfo, string imageName)
{
string imgPath = imageInfo.ConfigValue.ToString();
try
{
File.Delete(imgPath + "\\" + imageName);
}
catch (Exception ex)
{
logger.Error(ex.ToString());
return;
}
}
Here there is no need to do anything besides logging the error. Why then use return. Is it a mistake? Won't the method finish if you don't return explicitly? If there was more code after the catch clause would it be executed if the return wasn't there and the catch was used only for logging the error?
I'm not 100% sure that the catch stops further execution outside it's
scope but this is one of my questions so correct me if I'm wrong.
No, that's incorrect. Execution will continue normally after the catch block, unless some code inside the block changes the flow (e.g. throw or return).
Therefore return is necessary if you don't want execution to continue. Even if there is currently no code after the catch block, IMHO it's OK to make it more explicit that "handling this type of exception involves not executing any code after this point".
That said, you should be wary of catch (Exception ex) -- catching all types of exception should always be questioned and is almost always not quite the right thing to do (although in this case it's for logging, which is an "allowed exception to the rule").
I'm not 100% sure that the catch stops further execution outside it's scope but this is one of my questions so correct me if I'm wrong.
No, it doesn't. If the catch block doesn't either rethrow or return, execution will continue from the end of the try/catch statement.
In the sample you've given, the return statement is pointless. If there were code after the catch block, that would be a different matter, as the return statement would make the method return immediately.
It's not a mistake to have a return statement in a catch block like that, in that it's perfectly valid code, and will presumably still execute as intended - but it's definitely odd. It could well be that it was cut/paste from a method where the return statement was important.
(It's also almost always a bad idea to catch Exception, but that's a different matter.)
If there would be no return statement and further any code instead of that, then that code would have got executed. And you are allowed to return any thing from catch block. There is no restrictions for it.

Categories

Resources