Why are we not to throw these exceptions?

后端 未结 5 1721
名媛妹妹
名媛妹妹 2020-12-22 20:44

I came across this MSDN page that states:

Do not throw Exception, SystemException, NullReferenceException, or IndexOutOfRangeException intentionally f

5条回答
  •  佛祖请我去吃肉
    2020-12-22 21:19

    As you point out, in the article Creating and Throwing Exceptions (C# Programmming Guide) under the topic Things to Avoid When Throwing Exceptions, Microsoft does indeed list System.IndexOutOfRangeException as an exception type that should not be thrown intentionally from your own source code.

    In contrast, however, in the article throw (C# Reference), Microsoft seems to violate its own guidelines. Here is a method that Microsoft included in its example:

    static int GetNumber(int index)
    {
        int[] nums = { 300, 600, 900 };
        if (index > nums.Length)
        {
            throw new IndexOutOfRangeException();
        }
        return nums[index];
    }
    

    So, Microsoft itself isn't being consistent as it demonstrates the throwing of IndexOutOfRangeException in its documentation for throw!

    This leads me to believe that at least for the case of IndexOutOfRangeException, there may be occasions where that exception type can be thrown by the programmer and be considered an acceptable practice.

提交回复
热议问题