Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 950
bytecode77 Avatar asked Mar 20 '15 07:03

bytecode77


2 Answers

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, () => "");
like image 88
xanatos Avatar answered Sep 29 '22 13:09

xanatos


Here a little something that I've end up, to create a One Liner TryCatch

Usage

  var r = Task.TryCatch(() => _logic.Method01(param1, param2));

TryCatch definition

public static class Task
{

    public static TResult TryCatch<TResult>(Func<TResult> methodDelegate)
    {
        try
        {
            return methodDelegate();
        }
        catch (Exception ex)
        {
            // .. exception handling ...
        }

        return default(TResult);
    }
}
like image 29
Hugo Avatar answered Sep 29 '22 11:09

Hugo