Created
March 24, 2015 04:45
-
-
Save Keboo/7b62ba6fe4a1c1cf4294 to your computer and use it in GitHub Desktop.
An example of C# exception filter.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 ); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Output:
Throwing Fizz
Throwing Buzz
Finally Buzz
Buzz disposed
Finally Fizz
Fizz disposed
Fizz without filter