94

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
}
quip
  • 3,666
  • 3
  • 32
  • 45
  • 11
    Are you sure that you're not seeing a .NET exception (null reference) thrown on top of your own throw? – micahtan Feb 03 '10 at 21:56
  • 4
    You'd think the compiler would at least raise a warning about trying to directly "throw null;" – Andy White Feb 03 '10 at 21:59
  • No I'm not sure. The framework could very well be trying to do something with my object and when it is null, the framework throws a "Null Reference Exception" .. but ultimately, I want to be sure that "ex" can never be null – quip Feb 03 '10 at 22:00
  • 1
    @Andy: A warning may make sense for other situations in the langauge, but for `throw`, a statement whose *purpose* is to throw an exception in the first place, a warning doesn't add much value. – Mehrdad Afshari Feb 03 '10 at 22:16
  • @Mehrdad - yeah, but I doubt if any developer would purposely "throw null", and want to see a NullReferenceException. Maybe it should be a full build error, like an incorrect = comparison in an if statement. – Andy White Feb 03 '10 at 22:44
  • interesting that java also has the same behavior. check http://stackoverflow.com/questions/17576922/why-can-i-throw-null-in-java and http://stackoverflow.com/questions/6591910/why-throw-null-is-not-creating-compilation-error-in-java – Mel Jul 12 '13 at 12:05

7 Answers7

105

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.

Mehrdad Afshari
  • 414,610
  • 91
  • 852
  • 789
  • I suppose the best it could do would be to prohibit explicit phrases such as `throw null;`. – FrustratedWithFormsDesigner Feb 03 '10 at 22:00
  • 8
    Actually, it is entirely possible (in the CLR) for an object to be thrown that does not inherit from System.Exception. You can't do it in C# as far as I know, but it can be done via IL, C++/CLR, etc. See http://msdn.microsoft.com/en-us/library/ms404228.aspx for more information. – technophile Feb 03 '10 at 22:14
  • @technophile: Yes. I'm talking about the language here. In C#, it's not possible to throw an exception of other types but it's possible to catch it using a generic `catch { }` clause. – Mehrdad Afshari Feb 03 '10 at 22:17
  • 1
    While it wouldn't make sense for a compiler to refuse to accept a `throw` whose argument might be a null value, that wouldn't imply that `throw null` would have to be legal. A compiler could insist that a `throw` argument have a discernible class type. An expression like `(System.InvalidOperationException)null` should be valid at compile time (executing it should cause a `NullReferenceException`) but that doesn't mean that an untyped `null` should be acceptable. – supercat Jun 13 '12 at 23:39
  • @supercat: That's true, but the null in this case is implicitly typed as Exception (because it's used in a context where Exception is required). null is not valid at runtime, so NullReferenceException is thrown (as stated in Anon.'s answer). The exception thrown is not the one in the 'throw' statement. – John B. Lambe May 06 '18 at 14:57
  • @JohnB.Lambe: You're correct that the argument to `throw` is coerced to `Exception`, so there would be no need to have a compiler insist upon knowing the type. On the other hand, it's not difficult to imagine benefits to having another kind of throwable object that would not be caught be code expecting to catch an `Exception`. If the language resolved `throw`'s argument as it would that of a method, adding an "overload" for `throw(SevereError err);` would be a breaking change unless the language had imposed a constraint that the argument must be distinguishable between `Exception` and... – supercat May 06 '18 at 16:52
  • ...any other future class type that might be added for that purpose. Certainly the language could be designed to coerce the argument to `Exception` (as evidenced by the fact that it *was* designed that way) but that would not have been the only sensible design that would be compatible with just about all existing code that doesn't try to use `throw null;`. – supercat May 06 '18 at 16:53
  • In c#8, the compiler could (but I don't know if it does) assert that you can only throw a non-nullable reference. – Jeremy Lakeman Mar 05 '20 at 06:32
  • If I lookup the metadata for the Window class (WPF) it has a ShowDialog() method that has 'throw null;' – Paul McCarthy May 10 '22 at 15:43
32

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();
Anon.
  • 58,739
  • 8
  • 81
  • 86
8

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.

Brian Kennedy
  • 3,499
  • 3
  • 21
  • 27
  • 3
    Interesting. Could you post some code or maybe elude to what sits in your depth below that is doing this? – Peter Lillevold Dec 17 '12 at 18:25
  • I can't tell you if it is a CLR bug... it's hard to track down what in the guts of .NET threw null and why given you don't get an Exception with call stack or any other clues to go on. I just know that my outermost catch's now check for null Exception argument before using it. – Brian Kennedy Oct 18 '15 at 18:10
  • 3
    I suspect it IS a CLR bug, or due to bad unverifiable code. Correct CIL will only throw either a non-null object, or null (which becomes a NullReferenceException). – Demi Nov 19 '15 at 22:41
  • I also am using a service which is returning a null exception. Did you ever figure out how the null exception was being thrown? – themiDdlest Nov 11 '16 at 17:05
5

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.

Fitzchak Yitzchaki
  • 9,095
  • 12
  • 56
  • 96
2

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.

Steve Cooper
  • 20,542
  • 15
  • 71
  • 88
2

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.

Community
  • 1
  • 1
Peter Lillevold
  • 33,668
  • 7
  • 97
  • 131
  • @Brian Kennedy tells us in his comment above that we can catch null. – ProfK Dec 17 '12 at 06:23
  • 2
    @Tvde1 - I think the distinction here is that, yes, you can execute `throw null`. But that will not _throw an exception that is null_. Rather, because `throw null` tries to invoke methods on a null reference, this subsequently forces the runtime to throw a non-null instance of `NullReferenceException`. – Peter Lillevold Jul 01 '19 at 16:20
1

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.

Guvante
  • 18,775
  • 1
  • 33
  • 64