Skip to content

Instantly share code, notes, and snippets.

@Keboo
Created March 24, 2015 04:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Keboo/7b62ba6fe4a1c1cf4294 to your computer and use it in GitHub Desktop.
Save Keboo/7b62ba6fe4a1c1cf4294 to your computer and use it in GitHub Desktop.
An example of C# exception filter.
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using static System.Diagnostics.Debug;
namespace Example
{
[TestClass]
public class ExceptionFiltersFizzBuzz
{
[TestMethod]
public void ExceptionFilters()
{
try
{
BuggyMethod();
}
catch ( Exception ex ) when (FilterMethod())
{
WriteLine( ex.Message + " with filter" );
}
catch ( Exception ex )
{
WriteLine( ex.Message + " without filter" );
}
}
private void BuggyMethod()
{
using (var disposable = new MyDisposable( "Fizz" ))
{
try
{
disposable.ThrowingMethod();
}
finally
{
WriteLine( "Finally Fizz" );
}
}
}
private bool FilterMethod()
{
using (var disposable = new MyDisposable("Buzz"))
{
try
{
disposable.ThrowingMethod();
}
finally
{
WriteLine( "Finally Buzz" );
}
}
WriteLine( "Using filter" );
return true;
}
private class MyDisposable : IDisposable
{
private readonly string _Message;
public MyDisposable(string message)
{
_Message = message;
}
public void Dispose()
{
WriteLine( _Message + " disposed" );
}
public void ThrowingMethod()
{
WriteLine( "Throwing " + _Message );
throw new Exception( _Message );
}
}
}
}
@Keboo
Copy link
Author

Keboo commented Mar 25, 2015

Output:
Throwing Fizz
Throwing Buzz
Finally Buzz
Buzz disposed
Finally Fizz
Fizz disposed
Fizz without filter

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment