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 n
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.
In older c#:
Consider this syntax:
public void Add<T> ( T item ) => throw (hashSet.Add ( item ) ? null : new Exception ( "The item already exists" ));
I think it's way shorter than this:
public void Add<T> ( T item )
{
if (!hashSet.Add ( item ))
throw new Exception ( "The item already exists" );
}
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();
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.
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.
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.