Why does C# allow you to 'throw null'?

前端 未结 8 1606
滥情空心
滥情空心 2020-12-04 14:03

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

相关标签:
8条回答
  • 2020-12-04 14:46

    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.

    0 讨论(0)
  • 2020-12-04 14:46

    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" );
    }
    
    0 讨论(0)
  • 2020-12-04 14:48

    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();
    
    0 讨论(0)
  • 2020-12-04 14:50

    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.

    0 讨论(0)
  • 2020-12-04 14:55

    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.

    0 讨论(0)
  • 2020-12-04 14:56

    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.

    0 讨论(0)
提交回复
热议问题