Why does this program compile?
class Program
{
static void Main(string[] args)
{
throw null;
}
}
From 8.9.5 of the C# Language Specification,
A
throw
statement with an expression throws the value produced by evaluating the expression. The expression must denote a value of the class typeSystem.Exception
, of a class type that derives fromSystem.Exception
or of a type parameter type that hasSystem.Exception
(or a subclass thereof) as its effective base class. If evaluation of the expression producesnull
, aSystem.NullReferenceException
is thrown instead.
Obviously, null
evaluates to null
, so the last sentence is where this behavior is from, but how does it even get there? Attempting to throw other values that do not derive from System.Exception
results in a compiler error, error CS0155: The type caught or thrown must be derived from System.Exception
.
The top answer on the proposed duplicate begins with (emphasis mine):
Because the language specification expects an expression of type
System.Exception
there (therefore,null
is a valid in that context) ...
The expression null is System.Exception
evaluates to false, and produces a compiler warning warning CS0184: The given expression is never of the provided ('Exception') type
, so I'm comfortable making the assertion that null
isn't valid where a System.Exception
is required.