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
trystatement that encloses the throw point is examined. For each statementS, starting with the innermosttrystatement and ending with the outermosttrystatement, the following steps are evaluated:
If the try block of
Sencloses the throw point and ifShas one or morecatchclauses, thecatchclauses are examined in order of appearance to locate a suitable handler for the exception. The firstcatchclause that specifies the exception type or a base type of the exception type is considered a match. A generalcatchclause (§8.10) is considered a match for any exception type. If a matchingcatchclause is located, the exception propagation is completed by transferring control to the block of thatcatchclause.Otherwise, if the
tryblock or acatchblock ofSencloses the throw point and ifShas a finally block, control is transferred to the finally block. If thefinallyblock throws another exception, processing of the current exception is terminated. Otherwise, when control reaches the end point of thefinallyblock, 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