Reputation: 2887
I'm trying to figure out what this code sample in my book accomplishes. It says
Add an inner
try-catch
block in thefinally
block of the outer exception handler to prevent losing exception information:
private void PreventLossOfExeptionFormat()
{
try
{
// ...
}
catch(Exception e)
{
Console.WriteLine("Error message == " + e.Message);
throw;
}
finally
{
try
{
// ...
}
catch(Exception e)
{
Console.WriteLine("An unexpected error occured in the finally block. Error message: " + e.Message);
}
}
}
How is the outer exception getting into the inner one? I understand that in the outer catch
block it's getting thrown into the finally
block, but does it then get immediately caught in the catch
of the finally
block or what is the point of the try
inside there? Because if there is already an exception raised then there's nothing to try
...
Upvotes: 2
Views: 64
Reputation: 10929
Remember that the finally
block is always called, whether you have an outer exception or not (it's not triggered by the outer throw
).
The finally
block may trigger it's own exception, which is what the inner catch
will catch.
Upvotes: 2
Reputation: 62093
How is the outer exception getting into the inner one?
It is not.
I understand that in the outer catch block it's getting thrown into the finally block
Yes.
Because if there is already an exception raised then there's nothing to try
You seem to ignore what is obvious to read. The inner try catch in the outer finally is there to catch an exception in the lines that you marked as
// ...
I.e. finally is suppose to do something that MAY THROW IT'S OWN EXCEPTION.
Upvotes: 7