11

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?

5
  • I'm not sure why you'd want to? you should be trying to catch specific exceptions first, and then you shouldn't be using try catch to determine program flow either
    – Sayse
    Commented Mar 20, 2015 at 7:53
  • For instance, if you loop through processes'es MainModule, you get exceptions for all x64 processes. This is where this "operator" would kick in. It's for inline exception handling where no specific info about the exception (or bubbling) is necessary.
    – bytecode77
    Commented Mar 20, 2015 at 7:54
  • But then you are covering up an issue you have, you know that your program has an issue with x64 processes so you should try to fix those. If an exception has occured, then something has gone wrong and the time should be taken to handle it, so I don't think there is any shortcut that should be taken :)
    – Sayse
    Commented Mar 20, 2015 at 7:57
  • 1
    I don't want to discuss specific examples in which this is useful or if it is useful at all. I'm just looking for a proper way to implement this.
    – bytecode77
    Commented Mar 20, 2015 at 7:57
  • 1
    You have try? fooThatCanThrow ?? defaultValue in Swift, but not yet in C#. At least, nullability was added in C# 8.0, so it's a step closer to have your short syntax one day.
    – Cœur
    Commented Dec 7, 2018 at 10:44

2 Answers 2

10

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, () => "");
0
3

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);
    }
}

Not the answer you're looking for? Browse other questions tagged or ask your own question.