Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

throw-catch logic

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?

like image 910
DxCK Avatar asked Dec 28 '22 07:12

DxCK


2 Answers

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?

  1. By not throwing inside a finally block. That is always a bad idea.
  2. If you want to log in an inner catch block use throw; or pass the first exception as InnerException of the new one. That is why InnerException exists.
like image 108
Henk Holterman Avatar answered Jan 08 '23 13:01

Henk Holterman


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 statement S, starting with the innermost try statement and ending with the outermost try statement, the following steps are evaluated:

    • If the try block of S encloses the throw point and if S has one or more catch clauses, the catch clauses are examined in order of appearance to locate a suitable handler for the exception. The first catch clause that specifies the exception type or a base type of the exception type is considered a match. A general catch clause (§8.10) is considered a match for any exception type. If a matching catch clause is located, the exception propagation is completed by transferring control to the block of that catch clause.

    • Otherwise, if the try block or a catch block of S encloses the throw point and if S has a finally block, control is transferred to the finally block. If the finally block throws another exception, processing of the current exception is terminated. Otherwise, when control reaches the end point of the finally block, processing of the current exception is continued.

like image 41
Dirk Vollmar Avatar answered Jan 08 '23 13:01

Dirk Vollmar