In a try/catch/finally block like:
try
{
}
catch()
{
// code fails here
}
finally
{
}
So if there is an exception in the catch block, will finally always get called?
What if there is no finally, will the code after the catch block get run?
Answer: When an exception is thrown in the catch block, then the program will stop the execution. In case the program has to continue, then there has to be a separate try-catch block to handle the exception raised in the catch block.
A finally block always executes, regardless of whether an exception is thrown.
The finally block will in fact run after the catch block (even if the catch block rethrows the exception), which is what my snippet is trying to illustrate.
A finally block is always get executed whether the exception has occurred or not. If an exception occurs like closing a file or DB connection, then the finally block is used to clean up the code. We cannot say the finally block is always executes because sometimes if any statement like System.
Assuming the process doesn't terminate abruptly (or hang, of course), the finally block will always be executed.
If there's no finally block, the exception from the catch block will just be thrown up the stack. Note that the original exception which caused the catch block to be executed in the first place will be effectively lost.
Stack overflow exceptions
As Jared noted, a stack overflow will cause the finally block not to be executed. I believe this terminates the program abruptly, but I could be wrong. Here's sample code:
using System;
public class Test
{
static void Main()
{
// Give the stack something to munch on
int x = 10;
try
{
Main();
Console.WriteLine(x);
}
finally
{
Console.WriteLine("Finally");
}
}
}
Results:
Process is terminated due to StackOverflowException.
The finally block will always get executed. If you exclude the finally block, and an exception occurs inside the catch block, then no code after the catch block will execute, because essentially you're catch block will fail and generate an unhandled exception itself.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With