Search code examples
c#exceptionnull-coalescing-operator

A try-catch one liner (like "??" or ternary operator)


So we have ternary operators. Great! Then there's the ?? operator, which does a coalesce over a nullable variable.

Example:

string emptyIfNull = strValue ?? "";

Question: Is it possible to implement a simple operator like this for a try-catch?

Example:

string result = CoalesceException(someExpression, "");

public static T CoalesceException<T>(expression, defaultValue)
{
    try
    {
        return evaluate expression; // ?
    }
    catch
    {
        return defaultValue;
    }
}

Is it possible to implement a method that can be used as easily as possible, or even some kind of coalesce-like operator?


Solution

  • You can:

    public static T CoalesceException<T>(Func<T> func, T defaultValue = default(T))
    {
        try
        {
            return func();
        }
        catch
        {
            return defaultValue;
        }
    }
    

    but I'm not sure this is what you want...

    use:

    string emptyIfError = CoalesceException(() => someExpressionThatReturnsAString, "");
    

    for example...

    string shortString = null;
    
    string emptyIfError = CoalesceException(() => shortString.Substring(10), "");
    

    will return "" instead of NullReferenceException

    important

    The function, as written, will cause the "evaluation" of defaultValue always. Meaning:

    string Throws() { throw new Exception(); }
    
    string str1 = somethingTrue == true ? "Foo" : Throws();
    

    Here an exception won't be thrown, because Throws() won't be evalued. The same happens with the ?? operator.

    string str2 = CoalesceException(() => ((string)null).ToString(), Throws());
    

    This will cause an exception before entering in CoalesceException. Solution:

    public static T CoalesceException<T>(Func<T> func, Func<T> defaultValue = null)
    {
        try
        {
            return func();
        }
        catch
        {
            return defaultValue != null ? defaultValue() : default(T);
        }
    }
    

    Use:

    string emptyIfError = CoalesceException(() => someExpressionThatReturnsAString, () => "");