In C#, are there any built-in exceptions I shouldn't use?

前端 未结 6 2875
[愿得一人]
[愿得一人] 2021-02-20 10:08

Are there any Exceptions defined in the .NET Framework that I shouldn\'t throw in my own code, or that it is bad practice to? Should I write my own?

6条回答
  •  不知归路
    2021-02-20 10:31

    Most exception classes in the framework are not meant for reuse since they usually are crafted to signal some Framework specific error. Like those mentioned by @JaredPar, they are used by the framework to indicate certain states in the framework.

    There are literally tens, maybe hundreds, exceptions in the framework, so IMO it is more useful to list those that we should use. At the top of my head, these are those I actively use:

    • ArgumentException, ArgumentNullException and ArgumentOutOfRangeException
    • InvalidOperationException
    • NotSupportedException
    • NotImplementedException

    For other error conditions in user code, best practice is to create your own exception classes.

提交回复
热议问题