[What if ...] Filtered Exception Handling In C#
Wouldn’t it be cool if the C# compiler was able to support expressions inside of catch block handlers?
I imagine the syntax could look something like …
try
{
// Do some exception.
}
// $_ is the self-reference, not sure which
// character is best suited but it seems like
// a common token. We could check the
// type of the Exception. This would allow
// different exception types to be handled
// by the same block without additional effort.
// Since the compiler knows the types at
// compile-time probably could be implemented
// as syntatic sugar that expands out to a
// more traditional way of handling multiple
// exception types.
catch (ex => $_.GetType() == typeof(MyNamespace.SomeException)
|| $_.GetType() == typeof(MyNamespace.AnotherException))
{
//Handle MyNamespace.SomeException
// and MyNamespace.AnotherException.
}
// This would have to be a run-time filter,
// not sure if that would even be possible.
catch (ex => $_.GetType() == typeof(System.Exception)
&& $_.Message.Contains("Uh, oh"))
{
// Handle System.Exception when
// the message contains the text "Uh, oh".
}
// Traditional method.
catch(System.Exception ex)
{
// Current syntax to handle System.Exception.
}
I’d imagine the first example could be expanded by the compiler into separate Catch blocks much like Using and Lock are expanded to become Try/Finally blocks. The second example could probably be expanded into an If/Else blocks inside Catch blocks for each expected Exception type.
Categories: Uncategorized
c#, exceptions, ideas, lambda
Recent Comments