Exception Filter
C# does not support exception filter. However, VB and IL support it. To add exception filter to C#, we can build a function in VB or IL, then call it in C#.
The example below is one way we may implement the function to support exception filter. It asks the caller to provide four delegates, and call them at the right places.
Imports Microsoft.VisualBasic
Namespace Utility
Public Delegate Sub TryDelegate()
Public Delegate Function FilterDelegate(ByVal exception As System.Exception) As Boolean
Public Delegate Sub CatchDelegate(ByVal exception As System.Exception)
Public Delegate Sub FinallyDelegate()
Public Class ExceptionFilter
Inherits System.Object
Public Shared Sub TryFilterCatch(ByVal tryDelegate As TryDelegate, ByVal filterDelegate As FilterDelegate, ByVal catchDelegate As CatchDelegate, ByVal finallyDelegate As FinallyDelegate)
Try
tryDelegate()
Catch ex As System.Exception When catchDelegate <> Nothing And filterDelegate(ex)
catchDelegate(ex)
Finally
If (finallyDelegate <> Nothing) Then
finallyDelegate()
End If
End Try
End Sub
End Class
End Namespace
In C# we can call Utility.TryFilterCatch as the following:
using System;
using Utility;
namespace ExceptionFilterUsage
{
class Program
{
static void Main(string[] args)
{
TryDelegate tryDelegate = delegate()
{
Console.WriteLine("In try.");
throw new ApplicationException();
};
FilterDelegate filterDelegate = delegate(Exception e)
{
Console.WriteLine("In exception filter.");
if (e is ApplicationException)
{
Console.WriteLine("ApplicationException is thrown, which should never happen.");
return false;
}
return true;
};
CatchDelegate catchDelegate = delegate(Exception e)
{
Console.WriteLine("In Catch: Exception: {0}", e);
};
FinallyDelegate finallyDelegate = delegate()
{
Console.WriteLine("In finally.");
};
ExceptionFilter.TryFilterCatch(tryDelegate, filterDelegate, catchDelegate, finallyDelegate);
}
}
}