简体   繁体   中英

The null-coalescing operator and throw

I've just noticed that when using throw with the null-coalescing operator, you cannot just use the keyword "throw" on its own, an exception must be included with it. The following code demonstrates what I mean:

try
{
   return GetName();
}
catch (NameNotFoundException ex)
{
    string name = GetOtherName();
    // this is legal
    return name ?? throw ex;
    // whereas this is not
    return name ?? throw;
}

Is there any reason for this? Would it be because throw; doesn't constitute an expression, or is there more to it?

According to https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-7.0/throw-expression

a throw expression consists of the throw keyword followed by a null_coalescing_expression where the null_coalescing_expression

must denote a value of the class type System.Exception, of a class type that derives from System.Exception or of a type parameter type that has System.Exception (or a subclass thereof) as its effective base class. If evaluation of the expression produces null, a System.NullReferenceException is thrown instead

return name?? throw; does not satisfy this condition as only the throw expression would be allowed here, not a throw statement.

At least that's how I read this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM