为什么 C # 允许您“抛出 null”?

当编写一些特别复杂的异常处理代码时,有人问,您是否需要确保您的异常对象不为 null?我说,当然不是,但我决定试试。显然,您可以抛出 null,但它仍然会在某个地方变成异常。

为什么允许这样?

throw null;

在这个代码片段中,谢天谢地,“ ex”不是空的,但它有可能是空的吗?

try
{
throw null;
}
catch (Exception ex)
{
//can ex ever be null?


//thankfully, it isn't null, but is
//ex is System.NullReferenceException
}
18202 次浏览

Apparently, you can throw null, but it is still turned into an exception somewhere.

Attempting to throw a null object results in a (completely unrelated) Null Reference Exception.

Asking why you're allowed to throw null is like asking why you're allowed to do this:

object o = null;
o.ToString();

Because the language specification expects an expression of type System.Exception there (therefore, null is 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 is null or not. It would have to solve the halting problem. The runtime will have to deal with the null case anyway. See:

Exception ex = null;
if (conditionThatDependsOnSomeInput)
ex = new Exception();
throw ex;

They could, of course, make the specific case of throwing the null literal 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 null exception to be propagated, it does define the way exceptions are propagated:

The catch clauses, if any, are examined in order of appearance to locate a suitable handler for the exception. The first catch clause that specifies the exception type or a base type of the exception type is considered a match. A general catch clause is considered a match for any exception type. [...]

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 generic catch {} 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 the throw instruction. The description for that instruction is virtually identical to C# throw statement (except that it doesn't restrict the type of the object to System.Exception):

Description:

The throw instruction throws the exception object (type O) on the stack and empties the stack. For details of the exception mechanism, see Partition I.
[Note: While the CLI permits any object to be thrown, the CLS describes a specific exception class that shall be used for language interoperability. end note]

Exceptions:

System.NullReferenceException is thrown if obj is null.

Correctness:

Correct CIL ensures that object is always either null or an object reference (i.e., of type O).

I believe these are sufficient to conclude caught exceptions are never null.

I think maybe you can't -- when you try to throw null, it can't, so it does what it should in an error case, which is throw a null reference exception. So you're not actually throwning the null, you're failing to throw the null, which results in a throw.

Taken from here:

If you use this expression in your C# code it will throw a NullReferenceException. That is because the throw-statement needs an object of type Exception as its single parameter. But this very object is null in my example.

Trying to answer "..thankfully 'ex' is not null, but could it ever be?":

Since we arguably cannot throw exceptions that is null, a catch clause will also never have to catch an exception that is null. Thus, ex could never be null.

I see now that this question has in fact already been asked.

Remember that an exception includes details as to where the exception is thrown. Seeing as the constructor has no idea where it is to be thrown, then it only makes sense that the throw method injects those details into the object at the point the throw is. In other words the CLR is attempting to inject data into null, which triggers a NullReferenceException.

Not sure if this is exactly what is happening, but it explains the phenomenon.

Assuming this is true (and I can't think a better way to get ex to be null than throw null;), that would mean that ex cannot possibly be null.

While it may not be possible to throw null in C# because the throw will detect that and turn it into a NullReferenceException, it IS possible to receive null... I happen to be receiving that right now, which causes my catch (which was not expecting 'ex' to be null) to experience a null reference exception which then results in my app dying (since that was the last catch).

So, while we can't throw null from C#, the netherworld can throw null, so your outermost catch(Exception ex) better be prepared to receive it. Just FYI.