Inconsistent behaviour of throwing exceptions in finally block [duplicate] - c#

For a long time I thought that it allows me to free up all the resources in the finally block and I thought that if an exception happens in the try block, then the resources will still be free up in the finally block. But that seems not to be the case.
I have the following piece of code:
using System;
public sealed class Program
{
public static void Main()
{
try {
int zero = 0;
int i = 1/zero;
} finally {
Console.WriteLine("divide by zero"); //the line is never called
}
}
}
I never reach the line which prints to the console. That means that I will not be able to free up resource in finally block in this case on the exception being thrown inside the try block.
So, I believe there are two things: either I am missing something or the try + finally combination has no use cases in the C#. The second statement makes sense, because I will get the same functionality as is produced by the above code with the code below:
using System;
public sealed class Program
{
public static void Main()
{
int zero = 0;
int i = 1/zero;
Console.WriteLine("divide by zero"); //the line is never called
}
}
But I am afraid that I might be missing something here. So, could someone confirm that the combination is useless or prove that it is not, please?
UPDATE
After the comment which is able to call the finally block in its fiddle, I checked once more in the VS Code, and still I see no output.

You're assumptions are incorrect (sometimes) https://dotnetfiddle.net/hjqmOS
try-finally (C# Reference)
By using a finally block, you can clean up any resources that are
allocated in a try block, and you can run code even if an exception
occurs in the try block. Typically, the statements of a finally block
run when control leaves a try statement. The transfer of control can
occur 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.
There are cases when it doesn't run though
Within a handled exception, the associated finally block is guaranteed
to be run. However, if the exception is unhandled, execution of the
finally block is dependent on how the exception unwind operation is
triggered. That, in turn, is dependent on how your computer is set up.
Here is the important part
Usually, when an unhandled exception ends an application, whether or
not the finally block is run is not important. However, if you have
statements in a finally block that must be run even in that situation,
one solution is to add a catch block to the try-finally statement.
Alternatively, you can catch the exception that might be thrown in the
try block of a try-finally statement higher up the call stack.

try/catch/finally has nothing to do with freeing up resources. This is strictly application flow and error handling construct. You live in the managed code and garbage collector frees up resources. This construct does the following
try
{
int zero = 0;
int i = 1/zero;
}
catch (DividedByZeroException ex)
{
Console.WriteLine(Exception handled);
throw; // propagate ex to caller
}
finally
{
Console.WriteLine("Method ended execution"); // called with or without exception
}

I believe this is because you have VS to break on unhandled errors and thus VS steps in displaying the exception. If you compile it and run it manually on the command line I believe you will see "divide by zero". Also, instead of changing your VS settings, you can 'handle' the error and then should see the behavior you expect.
Example:
using System;
public sealed class Program
{
public static void Main()
{
try
{
int zero = 0;
int i = 1 / zero;
}
catch
{
}
finally
{
Console.WriteLine("divide by zero");
}
}
}

Related

Why the finally section is not executed in this official C# code? [duplicate]

For a long time I thought that it allows me to free up all the resources in the finally block and I thought that if an exception happens in the try block, then the resources will still be free up in the finally block. But that seems not to be the case.
I have the following piece of code:
using System;
public sealed class Program
{
public static void Main()
{
try {
int zero = 0;
int i = 1/zero;
} finally {
Console.WriteLine("divide by zero"); //the line is never called
}
}
}
I never reach the line which prints to the console. That means that I will not be able to free up resource in finally block in this case on the exception being thrown inside the try block.
So, I believe there are two things: either I am missing something or the try + finally combination has no use cases in the C#. The second statement makes sense, because I will get the same functionality as is produced by the above code with the code below:
using System;
public sealed class Program
{
public static void Main()
{
int zero = 0;
int i = 1/zero;
Console.WriteLine("divide by zero"); //the line is never called
}
}
But I am afraid that I might be missing something here. So, could someone confirm that the combination is useless or prove that it is not, please?
UPDATE
After the comment which is able to call the finally block in its fiddle, I checked once more in the VS Code, and still I see no output.
You're assumptions are incorrect (sometimes) https://dotnetfiddle.net/hjqmOS
try-finally (C# Reference)
By using a finally block, you can clean up any resources that are
allocated in a try block, and you can run code even if an exception
occurs in the try block. Typically, the statements of a finally block
run when control leaves a try statement. The transfer of control can
occur 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.
There are cases when it doesn't run though
Within a handled exception, the associated finally block is guaranteed
to be run. However, if the exception is unhandled, execution of the
finally block is dependent on how the exception unwind operation is
triggered. That, in turn, is dependent on how your computer is set up.
Here is the important part
Usually, when an unhandled exception ends an application, whether or
not the finally block is run is not important. However, if you have
statements in a finally block that must be run even in that situation,
one solution is to add a catch block to the try-finally statement.
Alternatively, you can catch the exception that might be thrown in the
try block of a try-finally statement higher up the call stack.
try/catch/finally has nothing to do with freeing up resources. This is strictly application flow and error handling construct. You live in the managed code and garbage collector frees up resources. This construct does the following
try
{
int zero = 0;
int i = 1/zero;
}
catch (DividedByZeroException ex)
{
Console.WriteLine(Exception handled);
throw; // propagate ex to caller
}
finally
{
Console.WriteLine("Method ended execution"); // called with or without exception
}
I believe this is because you have VS to break on unhandled errors and thus VS steps in displaying the exception. If you compile it and run it manually on the command line I believe you will see "divide by zero". Also, instead of changing your VS settings, you can 'handle' the error and then should see the behavior you expect.
Example:
using System;
public sealed class Program
{
public static void Main()
{
try
{
int zero = 0;
int i = 1 / zero;
}
catch
{
}
finally
{
Console.WriteLine("divide by zero");
}
}
}

Can i do Exception Handling in "Using" block?

public virtual IQueryable<Hubs> getribbons(bool includeChildObjects)
{
using (var dbHelper = new DbHelper())
{
DbDataReaderExtended reader = null;
try
{
const string sqlQuery = "Select * From [ribbons]";
reader = dbHelper.ExecuteReader(sqlQuery, CommandType.Text, true);
IList<Hubs> models = new List<Hubs>();
while (reader.Read())
{
var model = GetHubDataFromReader(reader);
if (includeChildObjects)
{
model.Satellites = GetAllSatellites(true,model.HubID).ToList();
}
models.Add(model);
}
return models.AsQueryable();
}
finally
{
if (reader != null) { reader.Close(); }
}
}
}
Here this functon is in Business logic Layer. Here i need to handle exceptions in catch block and log it there and after throw it to the function it has called first(Presentation Layer). and then in finally i need to close all the things.
Please show me how to do error handling Here.
i am very new to C# please give me some clarifications on this this will be very helpful for me.
Thanks in advance
Finally blocks will be called whether or not there is a throw.
Using statements will call IDisposable.Dispose() on anything that isn't null once the scope of the Using block is exited.
By using a finally block, you can clean up any resources that are allocated in a try block, and you can run code even if an exception occurs in the try block. Typically, the statements of a finally block run when control leaves a try statement. The transfer of control can occur 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.
Usually, when an unhandled exception ends an application, whether or not the finally block is run is not important. However, if you have statements in a finally block that must be run even in that situation, one solution is to add a catch block to the try-finally statement. Alternatively, you can catch the exception that might be thrown in the try block of a try-finally statement higher up the call stack. That is, you can catch the exception in the method that calls the method that contains the try-finally statement, or in the method that calls that method, or in any method in the call stack. If the exception is not caught, execution of the finally block depends on whether the operating system chooses to trigger an exception unwind operation.
using statement provides similar functionality(clear resources) only for IDisposable objects.
While in case of finally block, it will get executed regardless of whether or not there is an exception, provided that a catch block must be there in the call stack to catch the exception. Finally block can be used by developers to clear the resources on their own, that has not consumed IDispoable interface.

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.

Is finally block in C# a must?

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.

Use a 'try-finally' block without a 'catch' block

Are there situations where it is appropriate to use a try-finally block without a catch block?
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+
using is equivalent to try-finally. You will only use try-finally when you want to do some clean up inside finally and don't care about the exception.
The best approach will be
try
{
using(resource)
{
//Do something here
}
}catch(Exception)
{
//Handle Error
}
Doing so even clean up called by using fails, your code will not fail.
There are some condition when finally will not get executed.
If there is any StackOverflowException or ExecutingEngineException.
Process is killed from external source.
If you have, for example an unmanaged resource you create and use in the try block, you can use the finally block to ensure you release that resource. The finally block will always be executed despite what happens (e.g. exceptions) in the try block.
E.g. the lock(x) statement is really:
System.Threading.Monitor.Enter(x);
try { ... }
finally
{
System.Threading.Monitor.Exit(x);
}
The finally block will always get called to ensure the exclusive lock is released.
You need a finally block, when no matter which (if any) exceptions are caught or even if none are caught you still want to execute some code before the block exits. For instance, you might want to close an open file.
See Also try-finally
try/finally: when you do not want to handle any exceptions but want to ensure some action(s) occur whether or not an exception is thrown by called code.
I don't know anything about C#, but it seems that anything you could do with a try-finally, you could more elegantly do with a using statement. C++ doesn't even have a finally as a result of its RAII.
Here is a situation where you might want to use try finally: when you would normally use a using statement, but can't because you are calling a method by reflection.
This won't work
using (objMsg = Activator.CreateInstance(TypeAssist.GetTypeFromTypeName("omApp.MessagingBO")))
{
}
instead use
object objMsg = null;
try
{
objMsg
= Activator.CreateInstance(TypeAssist.GetTypeFromTypeName("myAssembly.objBO"));
strResponse = (string)objMsg.GetType().InvokeMember("MyMethod", BindingFlags.Public
| BindingFlags.Instance | BindingFlags.InvokeMethod, null, objMsg,
new object[] { vxmlRequest.OuterXml });
}
finally
{
if (objMsg!=null)
((IDisposable)objMsg).Dispose();
}
Have a look at the following link:
https://softwareengineering.stackexchange.com/questions/131397/why-use-try-finally-without-a-catch-clause
It depends on the architecture of your application and the operation you are performing in the block.
1.we can use the try block without catch but we should use the catch/finally,
any one of them.
2.We can't use only try block.

Categories

Resources