问题描述
要抛出异常,我通常使用内置的异常类,如: ArgumentNullException
和 NotSupportedException异常
。但是,有时我需要使用一个自定义异常,并在这种情况下,我写的:
To throw exceptions, I usually use built-in exception classes, e.g. ArgumentNullException
and NotSupportedException
. However, sometimes I need to use a custom exception and in that case I write:
class SlippedOnABananaException : Exception { }
class ChokedOnAnAppleException : Exception { }
等。然后,我扔在我的code捕捉这些。应该使用,而不是我 - 但是今天我遇到了 ApplicationException的
类?它是什么呢?
这似乎效率不高有很多有效的相同异常类有不同的名称(我通常不需要任何单独的功能)的。但我不喜欢追赶通用的 ApplicationException的
键,无需使用额外的code,以确定是什么错误的想法。
It does seem inefficient to have lots of effectively identical Exception classes with different names (I don't usually need any individual functionality). But I dislike the idea of catching a generic ApplicationException
and having to use extra code to determine what the error was.
应该在哪里 ApplicationException的
适合我的code?
Where should ApplicationException
fit in with my code?
推荐答案
按照言论在MSDN:
用户应用程序,而不是公共语言运行时,抛出从ApplicationException的类派生自定义异常。由应用程序与系统定义异常定义异常之间的ApplicationException的阶级区分。
如果你正在设计需要来创建其自己的异常的应用程序,建议您从Exception类派生自定义异常。它最初以为自定义异常应派生自ApplicationException的类;然而,在实践中,这还没有发现添加显著值。欲了解更多信息,请参阅最佳实践处理异常。
If you are designing an application that needs to create its own exceptions, you are advised to derive custom exceptions from the Exception class. It was originally thought that custom exceptions should derive from the ApplicationException class; however in practice this has not been found to add significant value. For more information, see Best Practices for Handling Exceptions.
从异常派生它们
。另外,我没有看到你的情况下,创造新的例外,只要它是必要的一个问题。如果你遇到一个情况下,已有的框架例外,使用,否则,推出自己。
Derive them from Exception
. Also, I don't see a problem with creating new exceptions for your cases, as long as it is warranted. If you encounter a case where there is already an exception in the framework, use that, otherwise, roll your own.
这篇关于什么是ApplicationException的在.NET?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!