Search code examples
c#exceptionfunctional-programmingswitch-expression

Is there a way to squeeze "throw new Exception()" into an object?


Some other advanced languages like Haskell and Perl 6 provide syntactic sugar that lets exceptions be thrown, even in a place where the syntax demands an object. It is acts as though it becomes a thrown exception when the value is used (which would be immediately, in the following very contrived example):

enum BuildMode { Debug, MemoryProfiling, Release };

bool IsDebugMode(BuildMode mode)
{
    return mode == BuildMode.Debug ? true
        : mode == BuildMode.MemoryProfiling ? true
        : mode == BuildMode.Release ? false
        : ThrowException<bool>("Unhandled mode: " + mode);
}

The above helper lets an exception be thrown from a place where a value is allowed but not a statement. I can write this function as follows, though it's not as cool as the Haskell or Perl 6 code, since there's no lazy evaluation:

T ThrowException<T>(string message)
{
#line hidden
    throw new Exception(message);
#line default
}

Is there any canonical way to do this, or any good reason not to?

Edit:

I actually didn't try using throw new Exception() as a value in C# 7 until after posting this. That is the answer, more or less. I'll leave this up, in case future people search for what is the C# equivalent to Perl 6's Failure class or Haskell's error.


Solution

  • C# 7.0 supports throw expressions:

    return mode == BuildMode.Debug ? true
        : mode == BuildMode.MemoryProfiling ? true
        : mode == BuildMode.Release ? false
        : throw new Exception("Unhandled mode: " + mode);
    

    There is no lazy evaluation, but you don't need your helper method anymore.