try
{
try
{
throw new Exception("From Try");
}
catch
{
throw new Exception("From Catch");
}
finally
{
throw new Exception("From Finally");
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
The above code's output is: From Finally
.
Why it's not From Catch
?
-or-
How can i catch & log from outside both exceptions?
Because the finally block executes after the catch block, overriding the exception.
And when an exception happens during the handling of an earlier one, the first one is lost.
How can i catch & log from outside both exceptions?
throw;
or pass the first exception as InnerException of the new one. That is why InnerException
exists.This is the behaviour as it is defined by the C# language specification. Handling of the exception thrown inside the try
block is aborted and instead the exception thrown in the finally
block will be handled.
The relevant section 8.9.5 The throw statement explains how exceptions are propagates:
In the current function member, each
try
statement that encloses the throw point is examined. For each statementS
, starting with the innermosttry
statement and ending with the outermosttry
statement, the following steps are evaluated:
If the try block of
S
encloses the throw point and ifS
has one or morecatch
clauses, thecatch
clauses are examined in order of appearance to locate a suitable handler for the exception. The firstcatch
clause that specifies the exception type or a base type of the exception type is considered a match. A generalcatch
clause (§8.10
) is considered a match for any exception type. If a matchingcatch
clause is located, the exception propagation is completed by transferring control to the block of thatcatch
clause.Otherwise, if the
try
block or acatch
block ofS
encloses the throw point and ifS
has a finally block, control is transferred to the finally block. If thefinally
block throws another exception, processing of the current exception is terminated. Otherwise, when control reaches the end point of thefinally
block, processing of the current exception is continued.
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