The function Try()
I've recently posted about two functions that I use sometimes to write less code: Void and Apply. Today I would like to share another one of the kind, a function that helps shortening try/catch
statements.
Consider the typical try/catch
statement:
try
{
session.Check();
Console.Error.WiteLine("OK");
}
catch (IOException e)
{
Console.Error.WiteLine("IOException: " + e.Message);
}
catch (Exception e)
{
Console.Error.WriteLine(e.Message);
}
Now let's introduce the function Try()
static Exception Try(Action action) {
try { action(); return null; } catch (Exception e) { return e; }
}
And see how it changes the try/catch
statement above:
Console.WriteLine(Try(() => session.Check()) switch {
IOException e => $"IOException: {e.Message}",
Exception e => e.Message,
_ => "OK"
});
It completely replaces the catch
statements with C#8 switch statement, which might be a good thing. After all, the switch
is more concise and at least equally powerful.
Try()
can be combined with Apply()
. As Try()
returns null when there is no exception, Apply()
will apply the action only when there is an exception:
try
{
session.Check();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
becomes
Try(() => session.Check()).Apply(e => Console.WriteLine(e.Message));
??
can chain several Try()
calls:
Try(() => session.Check()).Apply(_ => Console.WriteLine("Check has failed")) ??
Try(() => session.Send()).Apply(_ => Console.WriteLine("Send has failed"));