While writing some particularly complex exception handling code, someone asked, don’t you need to make sure that your exception object isn’t null? And I said, of course not, but then decided to try it. Apparently, you can throw null, but it is still turned into an exception somewhere.
Why is this allowed?
throw null;
In this snippet, thankfully ‘ex’ is not null, but could it ever be?
try
{
throw null;
}
catch (Exception ex)
{
//can ex ever be null?
//thankfully, it isn't null, but is
//ex is System.NullReferenceException
}
Because the language specification expects an expression of type
System.Exceptionthere (therefore,nullis a valid in that context) and doesn’t restrict this expression to be non-null. In general, there’s no way it could detect whether the value of that expression isnullor not. It would have to solve the halting problem. The runtime will have to deal with thenullcase anyway. See:They could, of course, make the specific case of throwing the
nullliteral invalid but that wouldn’t help much, so why waste specification space and reduce consistency for little benefit?Disclaimer (before I get slapped by Eric Lippert): This is my own speculation about the reasoning behind this design decision. Of course, I haven’t been in the design meeting 😉
The answer to your second question, whether an expression variable caught within a catch clause can ever be null: While the C# specification is silent about whether other languages can cause a
nullexception to be propagated, it does define the way exceptions are propagated:For
null, the bold statement is false. So, while purely based on what the C# spec says, we can’t say the underlying runtime won’t ever throw null, we can be sure that even if that’s the case, it’ll be only handled by the genericcatch {}clause.For C# implementations on the CLI, we can refer to the ECMA 335 specification. That document defines all exceptions that the CLI throws internally (none of which are
null) and mentions that user defined exception objects are thrown by thethrowinstruction. The description for that instruction is virtually identical to C#throwstatement (except that it doesn’t restrict the type of the object toSystem.Exception):I believe these are sufficient to conclude caught exceptions are never
null.