C# 创建我自己的自定义异常有哪些最佳实践?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/54851/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What are some best practices for creating my own custom exception?
提问by mattruma
In a follow-up to a previous questionregarding exceptions, what are best practices for creating a custom exception in .NET?
在上一个关于异常的问题的后续行动中,在 .NET 中创建自定义异常的最佳实践是什么?
More specifically should you inherit from System.Exception, System.ApplicationException or some other base exception?
更具体地说,您应该从 System.Exception、System.ApplicationException 还是其他一些基本异常继承?
采纳答案by Mark Cidade
Inherit from System.Exception
. System.ApplicationException
is useless and the design guidelines say "Do notthrow or derive from System.ApplicationException
."
继承自System.Exception
. System.ApplicationException
是没用的,设计指南说“不要抛出或派生自 ” System.ApplicationException
。
See http://blogs.msdn.com/kcwalina/archive/2006/06/23/644822.aspx
见http://blogs.msdn.com/kcwalina/archive/2006/06/23/644822.aspx
回答by Thomas Owens
I think the single most important thing to remember when dealing with exceptions at any level (making custom, throwing, catching) is that exceptions are only for exceptional conditions.
我认为在任何级别(自定义、抛出、捕获)处理异常时要记住的最重要的事情是异常仅适用于异常情况。
回答by Jon Limjap
The base exception from where all other exceptions inherit from is System.Exception, and that is what you should inherit, unless of course you have a use for things like, say, default messages of a more specific exception.
所有其他异常继承的基本异常是 System.Exception,这就是您应该继承的,除非您当然使用诸如更具体异常的默认消息之类的东西。
回答by Jon Limjap
There is a code snippet for it. Use that. Plus, check your code analysis afterwards; the snippet leaves out one of the constructors you should implement.
有一个代码片段。用那个。另外,事后检查你的代码分析;该代码段省略了您应该实现的构造函数之一。
回答by Jay Bazuzi
In the C# IDE, type 'exception' and hit TAB. This will expand to get you started in writing a new exception type. There are comments withs links to some discussion of exception practices.
在 C# IDE 中,输入“exception”并点击 TAB。这将扩展以帮助您开始编写新的异常类型。有一些评论和一些异常实践讨论的链接。
Personally, I'm a big fan of creating lots of small classes, at that extends to exception types. For example, in writing the Foo class, I can choose between:
就个人而言,我非常喜欢创建许多小类,并扩展到异常类型。例如,在编写 Foo 类时,我可以选择:
throw new Exception("Bar happened in Foo");
throw new FooException("Bar happened");
throw new FooBarException();
throw new Exception("Bar happened in Foo");
throw new FooException("Bar happened");
throw new FooBarException();
where
在哪里
class FooException : Exception
{
public FooException(string message) ...
}
and
和
class FooBarException : FooException
{
public FooBarException()
: base ("Bar happened")
{
}
}
I prefer the 3rd option, because I see it as being an OO solution.
我更喜欢第三个选项,因为我认为它是一个面向对象的解决方案。