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

前端 未结 8 1605
滥情空心
滥情空心 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

    In older c#:

    Consider this syntax:

    public void Add ( 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 item )
    {
        if (!hashSet.Add ( item ))
            throw new Exception ( "The item already exists" );
    }
    

提交回复
热议问题