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()




            // Set some program state

            // Do some work that can possibly throw an exception




            // Reset the program state




    public static void Main()






        catch (CustomBaseException ex)


            if (ex is CustomDontWantToCatchException)

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



                // 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


            Return True

        End If

End Function


Sub Main()




        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



  .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


Common Language Runtime


Leave a Comment
  • Please add 5 and 8 and type the answer here:
  • Post
  • あなたの精神年齢を占ってみよう!当サイトは、みんなの「精神年齢度」をチェックする性格診断のサイトです。精神年齢度には、期待以上の意外な結果があるかも??興味がある方はぜひどうぞ

  • マダムと甘い時間を過ごしてみませんか?性欲を持て余しているセレブたちは出張ホストサービスで男性を探し、セックスを求めているのです。ホスト希望の方なら容姿や年齢は一切不問!ご近所の女性を探して、多額の報酬をゲットしよう

  • 楽しく、気持ちよく絶頂を味わえることで若い女性から熟女の女性まで幅広い世代で爆発的な人気がある、スローセックス。当サイトはプレイに興味がある、あるいは試してみたいけれど相手がいない…といった方の支援サイトです。当サイトでSEXパートナーを探してみませんか

  • 恋することって怖くないですか?最近ちょっと臆病になってて…そういうの抜きでえっちなことしたくて…優しい人がいたらメール待ってます☆

  • さあ、今夏も新たな出会いを経験してみませんか?当サイトは円助交際の逆、つまり女性が男性を円助する『逆円助交際』を提供します。逆円交際を未経験の方でも気軽に遊べる大人のマッチングシステムです。年齢上限・容姿・経験一切問いません。男性の方は無料で登録して頂けます。貴方も新たな出会いを経験してみませんか

  • みんなの精神年齢を測定できる、メンタル年齢チェッカーで秘められた年齢がズバリわかっちゃう!かわいいあの子も実は精神年齢オバサンということも…合コンや話のネタに一度チャレンジしてみよう

  • 童貞卒業を考えているなら、迷わずココ!今まで童貞とヤッた事がない女性というのは意外と多いものです。そんな彼女たちは一度童貞とやってみたいと考えるのは自然な事と言えるでしょう。当サイトにはそんな好奇心旺盛な女性たちが登録されています

  • 素人ホストでは日頃のストレスを発散したい、もう一度恋がしたい、そういた女性が癒しを求めて登録されています。当サイトは癒やされたい女性・寂しい女性を癒やす男性が集うカップリングサイトです

  • 熟女だって性欲がある、貴方がもし人妻とSEXしてお金を稼ぎたいのなら、一度人妻ワイフをご利用ください。当サイトには全国各地からお金持ちのセレブたちが集まっています。女性から男性への報酬は、 最低15万円からと決めております。興味のある方は一度当サイト案内をご覧ください

  • 恥ずかしいけどやらしいことしたくてしょうがありません…誰か一緒にしてくれませんか?とりあえず連絡待ってます☆

  • 女の子のオナニーを手伝って報酬をもらう仕事に興味はありませんか?新感覚SNSの当サイトで見るだけで3万円、お手伝いで5万円の高額アルバイトを始めてみたい方は当サイトへどうぞ。

  • 家出娘や一人で寂しい子が書き込むSOS娘BBSでは彼女たちと遊んであげたり泊めてあげれる、優しい人を募集しています。見返りにHをしてくれる子も多く、いろんな理由がある少女があなたの助けを待っています。

  • 話題の小向美奈子ストリップを盗撮!入念なボディチェックをすり抜けて超小型カメラで撮影した神動画がアップ中!期間限定配信の衝撃的映像を見逃すな

  • mixiで禁止された「出会い」コミュニティーが復活しているのをご存じですか?当サイトでは規制前の楽しかった頃のミクシーを再現しているという好評を頂いております。会員数も右肩上がりに増えていますので、興味のある方はぜひご覧ください

  • 癒されたい女性や、寂しい素人女性を心も体も癒してあげるお仕事をご存じですか?女性宅やホテルに行って依頼主の女性とHしてあげるだけで高額の謝礼を手に入れる事が出来るのです。興味のある方は当サイトTOPページをご覧ください

Page 3 of 4 (52 items) 1234