Is the finally block pointless? [duplicate] - c#

This question already has answers here:
Why use finally in C#?
(13 answers)
Closed 6 years ago.
I'm teaching myself C# and I am up to studying the try, catch and finally. The book I'm using is discussing how the finally block runs regardless of whether or not the try block is successful. But, wouldn't code that is written outside of the catch block be run anyway even if it wasn't in finally? If so, what's the point of finally? This is the example program the book is providing:
class myAppClass
{
public static void Main()
{
int[] myArray = new int[5];
try
{
for (int ctr = 0; ctr <10; ctr++)
{
myArray[ctr] = ctr;
}
}
catch
{
Console.WriteLine("Exception caught");
}
finally
{
Console.WriteLine("Done with exception handling");
}
Console.WriteLine("End of Program");
Console.ReadLine();
}
}

These are scenarios where a finally is useful:
try
{
//Do something
}
catch (Exception e)
{
//Try to recover from exception
//But if you can't
throw e;
}
finally
{
//clean up
}
Usually you try to recover from exception or handle some types of exceptions, but if you cannot recover of you do not catch a specific type of exception the exception is thrown to the caller, BUT the finally block is executed anyway.
Another situation would be:
try
{
//Do something
return result;
}
finally
{
//clean up
}
If your code runs ok and no exceptions is thrown you can return from the try block and release any resources in the finally block.
In both cases if you put your code outside the try, it will never be executed.

Here is a simple example to show code that is written outside of the catch block does not run anyway even if it wasn't in finally!
try
{
try { throw new Exception(); }
finally { Console.WriteLine("finally"); }
Console.WriteLine("Where am I?");
}
catch { Console.WriteLine("catched"); }
and the output is
finally
catched
Please read the MSDN

The finally block executes code that needs to be run in either case. For example, you frequently rethrow an exception or otherwise go to other code. If the cleanup code for resources is not in a finally block, it will not be executed. You could also put this code in the catch block, but then you would be repeating the code after the try block anyway.

the finally block is incredibly helpful because it allows you to do resource clean up that otherwise wouldn't happen if you hit an exception.
e.g. (in pseudo)
try {
open socket
use socket
}
// note: no catch for any socket exceptions
finally {
delete socket // always executed
}

The whole point of the finally block is to wrap up stuff which you started. Suppose you opened a buffer in the try block, you shall close it in the finally. This is necessary so that even if an exception occurs and you exit from the try the resources are properly closed.
try
{
//Do Something
}
catch
{
//Catch Something
}
finally
{
//Always Do This
}
A lot of times the code inside your catch statement will either rethrow an exception or break out of the current function. If you don't have a finally block, "Always Do this" call won't execute that is if the code inside the catch statement issues a return or throws a new exception.

Related

Relationship between return keyword and finally keyword in c# [duplicate]

This question already has answers here:
Will code in a Finally statement fire if I return a value in a Try block?
(12 answers)
Closed 9 years ago.
i want to find out that the relationship between "return" and "finally" keywords. what is the execution order and what happens when exception occurs and return keyword is called after code block does some stuff, if there is two nested finally blocks as shown below,
try
{
try
{
}
catch (Exception)
{
//do some stuff
return;
}
finally
{
}
}
catch (Exception)
{
}
finally
{
}
From MSDN:
Typically, the statements of a finally block are executed when control leaves a try statement, whether the transfer of control occurs as a result of normal execution, of execution of a break, continue, goto, or return statement, or of propagation of an exception out of the try statement.
In your example, both finally blocks will execute. The inner one will execute first, and then the outer finally will execute.
No matter what happens, finally block is going to be executed.
As far as return is concerned, if a try block contains a return, it will actually do something like storing it in some variable, and return it at the end, after the execution of the finally block. like this:
try{
return xyz; //(i.e, temp = xyz;)
}
catch() {}
finally {}
return temp;
finally means run this code whatever happens
whatever could mean return or catch
Finally always gets executed. Whether you get exception or not your finally block will execute. And in your case both of your finall blocks will get executed.
If some error occurs in the inner try block, the control would goto the inner catch block, then the inner finally , then outer finally and then return the value that you did in the inner catch block.
Try debugging the code and you will get the flow
The finally block will always execute even in case of exception also. To understand consider below code
try
{
//sql connection opened
//execute a query ----> EXCEPTION OCCURRED HERE
//return the result
}catch(Exception ex)
{
throw ex;
}
finally{
//close the connection
}
above is the code that demonstrates widely used scenario of finally block. The connection to the database has to be closed even if exception occurs while executing the query.
If there is no exception then also the finally block will execute and then will return the result

If exception occurs in Catch block itself then how to handle it in C#?

//I have written code in Catch Block
try {
} catch(Excepetion ex) {
// I have written code here If Exception Occurs then how to handle it.
}
You can put a try catch inside the catch block, or you can simply throw the exception again. Its better to have finally block with your try catch so that even if an exception occurs in the catch block, finally block code gets executed.
try
{
}
catch(Excepetion ex)
{
try
{
}
catch
{
}
//or simply throw;
}
finally
{
// some other mandatory task
}
Finally block may not get executed in certain exceptions. You may see Constrained Execution Regions for more reliable mechanism.
The best way is to develop your own exceptions for different Layers of application and throw it with inner exception. It will be handled at the next layer of your application. If you think, that you can get a new Exception in the catch block, just re throw this exception without handling.
Let's imagine that you have two layers: Business Logic Layer (BLL) and Data Access Layer (DAL) and in a catch block of DAL you have an exception.
DAL:
try
{
}
catch(Excepetion ex)
{
// if you don't know how should you handle this exception
// you should throw your own exception and include ex like inner exception.
throw new MyDALException(ex);
}
BLL:
try
{
// trying to use DAL
}
catch(MyDALException ex)
{
// handling
}
catch(Exception ex)
{
throw new MyBLLException(ex);
}
try
{
// Some code here
}
catch (Exception ex)
{
try
{
// Some more code
}
catch (Exception ex)
{
}
}
For the lines of code that could throw an exception in catch block make extra explicit try..ctach block. Besides consider having finally block, to have lines to run by all means there. The same question may raise for the finally block. So if your code is likely to throw some exception in the finally block, you could also add try..catch there.
try
{
}
catch (Exception ex)
{
try
{
// code that is supposed to throw an exception
}
catch (Exception ex1)
{
}
// code that is not supposed to throw an exception
}
finally
{
try
{
// code that is supposed to throw an exception
}
catch (Exception ex1)
{
}
// code that is not supposed to throw an exception
}
Double-faulting often happens in well-designed 3g programming languages. Since protected mode and the 286, the general design for hardware languages is to reset the chip on a triple fault.
You are probably ok designing your way out of a double fault. Don't feel bad about having to do something to stop processing / report an error to the user in this case. If you run into a case where, eg., you catch an IO exception (reading/writing data) and then try to close the stream you're reading from, and that also fails, its not a bad pattern to fail dramatically and warn the user that something truly exceptional happened.
A catch block isn't special in any particular way. You will have to either use another try/catch block or not handle the error.
My friend Atul.. if you if write try..catch in catch block, and if again exception occurs in inner try..catch, same problem will raise again.
So address this issue you can handle those errors in application level events in Global.asax
check below links..
http://msdn.microsoft.com/en-us/library/24395wz3%28v=vs.100%29.aspx
http://msdn.microsoft.com/en-us/library/fwzzh56s%28v=vs.80%29.aspx
let me know if this works for you.. :)

try/catch/finally , How to prevent finally when i have return in my catch?

I have this code and i want to prevent finally execution
try
{
throw new Exception("Try Error!!!");
}
catch(Exception exp)
{
Console.WriteLine(exp.Message);
Console.ReadLine();
if(exp.Message == "Try Error!!!")
return;
}
finally
{
Console.WriteLine("Finally...");
Console.ReadLine();
}
But return doesn't work.
the finally doesn't run only in following three conditions :
The System.exit() is called from the try or catch block.
There is an infinite loop inside the try block.
The system crashes or power loss while executing the try block.
for all other conditions .... the finally is always executed... having a boolean variable to control the execution of finally code is a clever approach... go for it...
That's the point of finally - it always runs.
try this:
bool runfinally = true;
try {
throw new Exception("test");
} catch {
runfinally = false;
} finally {
if(runfinally) {
// do stuff.
}
}
Why would you want to do that?
Finally is there so it allways runs and does some finishing work which has to be done anyway, if ou want the code to be executed only when the try runs then write in in the try statement, otherwise if only when it fails then in the catch one. Code that has to tun in both cases has to be written in the finally section.
The only way is to set a flag variable that your finally code tests, e.g.:
bool handled = false;
try
{
throw new Exception("Try Error!!!");
}
catch(Exception exp)
{
Console.WriteLine(exp.Message);
Console.ReadLine();
if (exp.Message == "Try Error!!!")
{
handled = true;
return; // This isn't really necessary unless you have code below it you're not showing
}
}
finally
{
if (!handled)
{
Console.WriteLine("Finally...");
Console.ReadLine();
}
}
...but I'd really consider revisiting your logic so you don't need to do that. The whole point of finally is that no matter what happens within the try block, that finally code will run, whether you return early from the code in the try block, or an exception occurs, or you return from within the catch block.
The whole point of finally is that it runs regardless of how the try/catch block executed. One workaround can be something like this:
bool runfinallycode = true;
try
{
throw new Exception("Try Error!!!");
}
catch(Exception exp)
{
Console.WriteLine(exp.Message);
Console.ReadLine();
if(exp.Message == "Try Error!!!")
runfinallycode = false;
}
finally
{
if( runfinallycode )
{
Console.WriteLine("Finally...");
Console.ReadLine();
}
}
Finally gets executed no matter what happens in the try catch block. It's meant that way so that you can free up resources before you exit the function.
System.exit() can be used to avoid the execution of the finally block Finally Block.
But if your condition is that the execution should not be hindered, then please do reframe the question.
But your return is in a if clause so it will not always work. Try putting it outside the if in catch

Where the finally is necessary?

I know how to use try-catch-finally. However I do not get the advance of using finally as I always can place the code after the try-catch block.
Is there any clear example?
It's almost always used for cleanup, usually implicitly via a using statement:
FileStream stream = new FileStream(...);
try
{
// Read some stuff
}
finally
{
stream.Dispose();
}
Now this is not equivalent to
FileStream stream = new FileStream(...);
// Read some stuff
stream.Dispose();
because the "read some stuff" code could throw an exception or possibly return - and however it completes, we want to dispose of the stream.
So finally blocks are usually for resource cleanup of some kind. However, in C# they're usually implicit via a using statement:
using (FileStream stream = new FileStream(...))
{
// Read some stuff
} // Dispose called automatically
finally blocks are much more common in Java than in C#, precisely because of the using statement. I very rarely write my own finally blocks in C#.
You need a finally because you should not always have a catch:
void M()
{
var fs = new FileStream(...);
try
{
fs.Write(...);
}
finally
{
fs.Close();
}
}
The above method does not catch errors from using fs, leaving them to the caller. But it should always close the stream.
Note that this kind of code would normally use a using() {} block but that is just shorthand for a try/finally. To be complete:
using(var fs = new FileStream(...))
{
fs.Write(...);
} // invisible finally here
try
{
DoSomethingImportant();
}
finally
{
ItIsRidiculouslyImportantThatThisRuns();
}
When you have a finally block, the code therein is guaranteed to run upon exit of the try. If you place code outside of the try/catch, that is not the case. A more common example is the one utilized with disposable resources when you use the using statement.
using (StreamReader reader = new StreamReader(filename))
{
}
expands to
StreamReader reader = null;
try
{
reader = new StreamReader(filename);
// do work
}
finally
{
if (reader != null)
((IDisposable)reader).Dispose();
}
This ensures that all unmanaged resources get disposed and released, even in the case of an exception during the try.
*Note that there are situations when control does not exit the try, and the finally would not actually run. As an easy example, PowerFailureException.
Update: This is actually not a great answer. On the other hand, maybe it is a good answer because it illustrates a perfect example of finally succeeding where a developer (i.e., me) might fail to ensure cleanup properly. In the below code, consider the scenario where an exception other than SpecificException is thrown. Then the first example will still perform cleanup, while the second will not, even though the developer may think "I caught the exception and handled it, so surely the subsequent code will run."
Everybody's giving reasons to use try/finally without a catch. It can still make sense to do so with a catch, even if you're throwing an exception. Consider the case* where you want to return a value.
try
{
DoSomethingTricky();
return true;
}
catch (SpecificException ex)
{
LogException(ex);
return false;
}
finally
{
DoImportantCleanup();
}
The alternative to the above without a finally is (in my opinion) somewhat less readable:
bool success;
try
{
DoSomethingTricky();
success = true;
}
catch (SpecificException ex)
{
LogException(ex);
success = false;
}
DoImportantCleanup();
return success;
*I do think a better example of try/catch/finally is when the exception is re-thrown (using throw, not throw ex—but that's another topic) in the catch block, and so the finally is necessary as without it code after the try/catch would not run. This is typically accomplished with a using statement on an IDisposable resource, but that's not always the case. Sometimes the cleanup is not specifically a Dispose call (or is more than just a Dispose call).
The code put in the finally block is executed even when:
there are return statements in the try or catch block
OR
the catch block rethrows the exception
Example:
public int Foo()
{
try
{
MethodThatCausesException();
}
catch
{
return 0;
}
// this will NOT be executed
ReleaseResources();
}
public int Bar()
{
try
{
MethodThatCausesException();
}
catch
{
return 0;
}
finally
{
// this will be executed
ReleaseResources();
}
}
you don't necessarily use it with exceptions. You may have try/finally to execute some clean up before every return in the block.
The finally block always is executed irrespective of error obtained or not. It is generally used for cleaning up purposes.
For your question, the general use of Catch is to throw the error back to caller, in such cases the code is finally still executes.
The finally block will always be executed even if the exception is re-thrown in the catch block.
If an exception occurs (or is rethrown) in the catch-block, the code after the catch won't be executed - in contrast, code inside a finally will still be executed.
In addition, code inside a finally is even executed when the method is exited using return.
Finally is especially handy when dealing with external resources like files which need to be closed:
Stream file;
try
{
file = File.Open(/**/);
//...
if (someCondition)
return;
//...
}
catch (Exception ex)
{
//Notify the user
}
finally
{
if (file != null)
file.Close();
}
Note however, that in this example you could also use using:
using (Stream file = File.Open(/**/))
{
//Code
}
For example, during the process you may disable WinForm...
try
{
this.Enabled = false;
// some process
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
this.Enabled = true;
}
I am not sure how it is done in c#, but in Delphi, you will find "finally" very often. The keyword is manual memory management.
MyObject := TMyObject.Create(); //Constructor
try
//do something
finally
MyObject.Free();
end;

Why use finally in C#?

Whatever is inside finally blocks is executed (almost) always, so what's the difference between enclosing code into it or leaving it unclosed?
The code inside a finally block will get executed regardless of whether or not there is an exception. This comes in very handy when it comes to certain housekeeping functions you need to always run like closing connections.
Now, I'm guessing your question is why you should do this:
try
{
doSomething();
}
catch
{
catchSomething();
}
finally
{
alwaysDoThis();
}
When you can do this:
try
{
doSomething();
}
catch
{
catchSomething();
}
alwaysDoThis();
The answer is that a lot of times the code inside your catch statement will either rethrow an exception or break out of the current function. With the latter code, the "alwaysDoThis();" call won't execute if the code inside the catch statement issues a return or throws a new exception.
Most advantages of using try-finally have already been pointed out, but I thought I'd add this one:
try
{
// Code here that might throw an exception...
if (arbitraryCondition)
{
return true;
}
// Code here that might throw an exception...
}
finally
{
// Code here gets executed regardless of whether "return true;" was called within the try block (i.e. regardless of the value of arbitraryCondition).
}
This behaviour makes it very useful in various situations, particularly when you need to perform cleanup (dispose resources), though a using block is often better in this case.
Because finally will get executed even if you do not handle an exception in a catch block.
any time you use unmanaged code requests like stream readers, db requests, etc; and you want to catch the exception then use try catch finally and close the stream, data reader, etc. in the finally, if you don't when it errors the connection doesn't get closed, this is really bad with db requests
SqlConnection myConn = new SqlConnection("Connectionstring");
try
{
myConn.Open();
//make na DB Request
}
catch (Exception DBException)
{
//do somehting with exception
}
finally
{
myConn.Close();
myConn.Dispose();
}
if you don't want to catch the error then use
using (SqlConnection myConn = new SqlConnection("Connectionstring"))
{
myConn.Open();
//make na DB Request
myConn.Close();
}
and the connection object will be disposed of automatically if there is an error, but you don't capture the error
Finally statements can execute even after return.
private int myfun()
{
int a = 100; //any number
int b = 0;
try
{
a = (5 / b);
return a;
}
catch (Exception ex)
{
Response.Write(ex.Message);
return a;
}
// Response.Write("Statement after return before finally"); -->this will give error "Syntax error, 'try' expected"
finally
{
Response.Write("Statement after return in finally"); // --> This will execute , even after having return code above
}
Response.Write("Statement after return after finally"); // -->Unreachable code
}
finally, as in:
try {
// do something risky
} catch (Exception ex) {
// handle an exception
} finally {
// do any required cleanup
}
is a guaranteed opportunity to execute code after your try..catch block, regardless of whether or not your try block threw an exception.
That makes it perfect for things like releasing resources, db connections, file handles, etc.
i will explain the use of finally with a file reader exception Example
with out using finally
try{
StreamReader strReader = new StreamReader(#"C:\Ariven\Project\Data.txt");
Console.WriteLine(strReader.ReadeToEnd());
StreamReader.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
in the above example if the file called Data.txt is missing, an exception will be thrown and will be handled but the statement called StreamReader.Close(); will never be executed.
Because of this resources associated with reader was never released.
To solve the above issue, we use finally
StreamReader strReader = null;
try{
strReader = new StreamReader(#"C:\Ariven\Project\Data.txt");
Console.WriteLine(strReader.ReadeToEnd());
}
catch (Exception ex){
Console.WriteLine(ex.Message);
}
finally{
if (strReader != null){
StreamReader.Close();
}
}
Happy Coding :)
Note:
"#" is used to create a verbatim string, to avoid error of "Unrecognized escape sequence".
The # symbol means to read that string literally, and don't interpret control characters otherwise.
Say you need to set the cursor back to the default pointer instead of a waiting (hourglass) cursor. If an exception is thrown before setting the cursor, and doesn't outright crash the app, you could be left with a confusing cursor.
Sometimes you don't want to handle an exception (no catch block), but you want some cleanup code to execute.
For example:
try
{
// exception (or not)
}
finally
{
// clean up always
}
The finally block is valuable for cleaning up any resources allocated in the try block as well as running any code that must execute even if there is an exception. Control is always passed to the finally block regardless of how the try block exits.
Ahh...I think I see what you're saying! Took me a sec...you're wondering "why place it in the finally block instead of after the finally block and completely outside the try-catch-finally".
As an example, it might be because you are halting execution if you throw an error, but you still want to clean up resources, such as open files, database connections, etc.
Control Flow of the Finally Block is either after the Try or Catch block.
[1. First Code]
[2. Try]
[3. Catch]
[4. Finally]
[5. After Code]
with Exception
1 > 2 > 3 > 4 > 5
if 3 has a Return statement
1 > 2 > 3 > 4
without Exception
1 > 2 > 4 > 5
if 2 has a return statement
1 > 2 > 4
As mentioned in the documentation:
A common usage of catch and finally together is to obtain and use resources in a try block, deal with exceptional circumstances in a catch block, and release the resources in the finally block.
It is also worth reading this, which states:
Once a matching catch clause is found, the system prepares to transfer control to the first statement of the catch clause. Before execution of the catch clause begins, the system first executes, in order, any finally clauses that were associated with try statements more nested that than the one that caught the exception.
So it is clear that code which resides in a finally clause will be executed even if a prior catch clause had a return statement.

Categories