我可以从我的应用程序中抛出哪些内置的.NET异常? [英] Which built-in .NET exceptions can I throw from my application?

查看:79
本文介绍了我可以从我的应用程序中抛出哪些内置的.NET异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我需要在我的应用程序中抛出异常我可以使用哪些内置的.NET异常类?他们都是公平的游戏吗?

解决方案

请参阅创建和抛出异常



抛出内置异常,它说: p>


不要从您自己的源代码有意地抛出System.Exception,System.SystemException,System.NullReferenceException或System.IndexOutOfRangeException。



不要抛出常规异常



如果您在库或框架中抛出一般异常类型(例如Exception或SystemException),则会强制消费者捕获所有异常,包括他们不知道如何处理的未知异常。



相反,要么抛出一个已经存在于框架中的更多派生类型,要么创建自己从Exception派生的类型。


这个博客条目也有一些有用的指导。



此外,FxCop代码分析定义了一个不引起异常的列表,如这里介绍,它建议:


以下异常类型太普遍,无法向用户提供足够的信息:




  • System.Exception

  • System.ApplicationException

  • System.SystemException



以下异常类型被保留并显示只能由公共语言运行时抛出:




  • System.ExecutionEngineException

  • System.IndexOutOfRangeException

  • System.NullReferenceException

  • System.OutOfMemoryException


所以在理论上你可以提出任何其他的框架异常类型,让你清楚地了解Microsoft所描述的异常的意图(见MSDN文档)。


$ b $注意,这些是指导原则,正如其他人所说,有关System.IndexOutOfRangeException的争论(即许多开发人员抛出这个异常)。


If I need to throw an exception from within my application which of the built-in .NET exception classes can I use? Are they all fair game? When should I derive my own?

解决方案

See Creating and Throwing Exceptions.

On throwing built-in exceptions, it says:

Do not throw System.Exception, System.SystemException, System.NullReferenceException, or System.IndexOutOfRangeException intentionally from your own source code.

and

Do Not Throw General Exceptions

If you throw a general exception type, such as Exception or SystemException in a library or framework, it forces consumers to catch all exceptions, including unknown exceptions that they do not know how to handle.

Instead, either throw a more derived type that already exists in the framework, or create your own type that derives from Exception."

This blog entry also has some useful guidelines.

Also, FxCop code analysis defines a list of "do not raise exceptions" as described here. It recommends:

The following exception types are too general to provide sufficient information to the user:

  • System.Exception
  • System.ApplicationException
  • System.SystemException

The following exception types are reserved and should be thrown only by the common language runtime:

  • System.ExecutionEngineException
  • System.IndexOutOfRangeException
  • System.NullReferenceException
  • System.OutOfMemoryException

So in theory you can raise any other framework exception type, providing you clearly understand the intent of the exception as described by Microsoft (see MSDN documentation).

Note, these are "guidelines" and as some others have said, there is debate around System.IndexOutOfRangeException (ie many developers throw this exception).

这篇关于我可以从我的应用程序中抛出哪些内置的.NET异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆