Catch, Rethrow and Filters - Why you should care?

Catch, Rethrow and Filters - Why you should care?

  • Comments 52

 

A very common pattern in the usage of managed exception handling is that of catching an exception, inspecting it's type and rethrowing it once you realize it was not the exception you wanted to handle. Below is such an example (and should be avoided in preference to another approach described further below in the writeup) that uses CustomBaseException as the base type of an exception hierarchy and CustomDontWantToCatchException as a type that derives from the base class that you wouldn’t want to catch:

 

    private static void Foo()

    {

        try

        {

            // Set some program state

            // Do some work that can possibly throw an exception

        }

        finally

        {

            // Reset the program state

        }

    }

 

    public static void Main()

    {

        try

        {

            Foo();

        }

        catch (CustomBaseException ex)

        {

            if (ex is CustomDontWantToCatchException)

                throw; // Rethrow since we dont want to handle exceptions we aren’t interested in!

            else

            {

                // handle the exception

            }

        }

    }

 

Managed exception handling comprises of two passes:

 

1.       In the first pass, the CLR looks for a handler for the thrown exception. When one is found, it begins the second pass.

2.       In the second pass, also known as the unwind pass, it invokes all the termination handlers (e.g. managed finally/fault blocks, along with the native counterparts like __finally, destructors of stack allocated objects) that lie between the handler of the exception and the point at which the exception was thrown.

 

Thus, if you use a pattern like the one above, only to rethrow an exception since it was decided not to deal with it, prior to your [catch] handler being invoked, the termination handlers will be invoked. These handlers would end up doing the cleanup (like reset program state) before control is returned to the handler that agreed to handle the exception. Hence, by the time you enter the catch block, like in the example above, program state would have been modified since the finally in Foo would have been invoked. Thus, type handlers (like a catch clause) are invoked after the second pass has successfully been completed even though they are located in the first pass.

 

Assuming the exception was CustomDontWantToCatchException, the catch block proceeds to rethrow it, expecting it to go unhandled. When exceptions go unhandled, it is a good thing - and that is because we get the actual program state at the time when the exception was thrown. However, when pattern like the one above is used to rethrow conditionally, the program state gets modified and when the rethrown exception becomes unhandled, you will see actual program state from the point of rethrow and not the original throw.

 

So, how do we address such conditional exception processing without affecting program state for better diagnostics (in case the exception goes unhandled)?

 

Filters! Not really well known and not used a lot, managed filters are invoked by the CLR in the first pass when it is looking for a handler for an exception. While  a type handler is associated with a concrete type based upon which the CLR will decide whether the handler is capable of handling the exception or not, a filter can have custom logic to determine whether it wants to handle the exception or not.

 

When a filter is found in the first pass, the CLR will pass it the exception object corresponding to the thrown exception. The filter can then decide whether it wants to handle the exception or not, by accessing the state on the exception object (Note: accessing global program state from within a filter may lead to unexpected results. Thus, any such accesses should be avoided from within a filter). Once it has decided, a boolean is returned back to the CLR indicate its decision. If it agrees to handle the exception, the CLR will proceed to trigger the second (or unwind) pass. But if it decides not to handle the exception, the CLR will continue look further on the stack for any handler that may want to handle the exception. If none are found, the exception becomes unhandled and CLR's unhandled exception processing kicks in.

 

Hence, instead of catching all exceptions as shown in the example above (or using base type of a given exception hierarchy) and then rethrowing the caught exception because you didn’t want to handle it, write a filter that will enable you to do just that without triggering the second pass and modifying program state in the process.

 

And how does one write a managed filter?


While the CLR support filters, not all managed languages support it - IL and VB, for instance, do support it but C# does not! Rewriting the Main method above in VB , we can see how easy it can be to inspect an exception on the fly without affecting the program state and conditionally deciding whether, or not, to handle the exception:

 

 Function ShouldCatch(ByVal exception As CustomBaseException) As Boolean

 

        If TypeOf (exception) Is CustomDontWantToCatchException Then

            Return False

        Else

            Return True

        End If
 

End Function

 

Sub Main()

        Try

            Foo()

 

        Catch ex As CustomBaseException When ShouldCatch(ex) = True

 

            Console.WriteLine("Caught exception!")

 

        End Try

End Sub

 

VB's Catch keyword, when used with the When keyword, emits an IL filter as shown in the IL disassembly of the Main function below:

 

.method public static void  Main() cil managed

{

  .entrypoint

  .custom instance void [mscorlib]System.STAThreadAttribute::.ctor() = ( 01 00 00 00 )

  // Code size       62 (0x3e)

  .maxstack  3

  .locals init ([0] class ConsoleApplication1.CustomBaseException ex)

  IL_0000:  nop

  IL_0001:  nop

  IL_0002:  call       void ConsoleApplication1.Module1::Foo()

  IL_0007:  nop

  IL_0008:  leave.s    IL_003b

  IL_000a:  isinst     ConsoleApplication1.CustomBaseException

  IL_000f:  dup

  IL_0010:  brtrue.s   IL_0016

  IL_0012:  pop

  IL_0013:  ldc.i4.0

  IL_0014:  br.s       IL_0026

  IL_0016:  dup

  IL_0017:  stloc.0

  IL_0018:  call       void [Microsoft.VisualBasic]Microsoft.VisualBasic.CompilerServices.ProjectData::SetProjectError(class [mscorlib]System.Exception)

  IL_001d:  ldloc.0

  IL_001e:  call       bool ConsoleApplication1.Module1::ShouldCatch(class ConsoleApplication1.CustomBaseException)

  IL_0023:  ldc.i4.0

  IL_0024:  cgt.un

  IL_0026:  endfilter

  IL_0028:  pop

  IL_0029:  ldstr      "Caught exception!"

  IL_002e:  call       void [mscorlib]System.Console::WriteLine(string)

  IL_0033:  nop

  IL_0034:  call       void [Microsoft.VisualBasic]Microsoft.VisualBasic.CompilerServices.ProjectData::ClearProjectError()

  IL_0039:  leave.s    IL_003b

  IL_003b:  nop

  .try IL_0002 to IL_000a filter IL_000a handler IL_0028 to IL_003b

  IL_003c:  nop

  IL_003d:  ret

} // end of method Module1::Main


You can see that, towards the end of the disassembly, we have the IL regions (bold and highlighted in yellow, between IL offset 3B and 3C) defining what constitutes the try block, the filter and if the exception is going to be handled, the filter-handler as well. Depending upon what the filter returns, after invoking ShouldCatch (which, in this example, decides whether the exception should be handled based upon its type), the CLR will either  execute the filter-handler or continue to go up the stack looking for exception handlers.

 

To conclude, for such exception inspection patterns that need to handle exception conditionally, use filters as they enable you to do the same as catching and rethrowing pattern without affecting the program state. It’d be great if they were in C#, but they’re not, so really consider using IL filters or VB where you need this functionality.

 

Gaurav Khanna

Developer,

Common Language Runtime

 

Leave a Comment
  • Please add 2 and 6 and type the answer here:
  • Post
  • 最近してないし欲求不満です。一緒にいやらしいことしませんか?エッチには自信あるよ(笑) nyaon.chuki@docomo.ne.jp メール待ってるよ☆

  • 女性向け風俗サイトで出張デリバリーホストをしてみませんか?時給2万円以上の超高額アルバイトです。無料登録をしてあとは女性からの呼び出しを待つだけなので、お試し登録も歓迎です。興味をもたれた方は今すぐどうぞ。

  • 最近TVや雑誌で紹介されている家出掲示板では、全国各地のネットカフェ等を泊り歩いている家出娘のメッセージが多数書き込みされています。彼女たちはお金がないので掲示板で知り合った男性の家にでもすぐに泊まりに行くようです。あなたも書き込みに返事を返してみませんか

  • あなたの性格を、動物に例えて占っちゃいます。もしかしたらこんな動物かも!?動物占いをうまく使って、楽しい人間関係を築いてください

  • あなたの真のH度を診断できるHチェッカー!コンパや飲み会で盛り上がること間違いなしのおもしろツールでみんなと盛り上がろう

  • よーやくプロフ持ちになれました。私の事気になった方がいましたら気軽にメールください。恋バナとか好きなんでよろしくでぇす。zuttozuttoissyodayo@docomo.ne.jp

  • @David Nelson

    Why did Mads consider it an anti-pattern? Consider the following pretty common code:

    try{/* something HTTPish */}

    catch(HttpException e)

    {

      if(e.ErrorCode != 503)

          throw;

      //If 503 (Unavailable), fetch from backup server

    }

    where I'd prefer (instead of the catch clause)

       filter(HttpException e) where e.ErrorCode != 503 (or similar)

    How is Mads arguing that this case should be dealt with? The standard solution's "rethrow" statement clearly messes stack traces up.

Page 4 of 4 (52 items) 1234