什么是行业标准最好在C#中实现自定义异常的做法? [英] What are industry standard best practices for implementing custom exceptions in C#?
问题描述
什么是行业标准为C#实现自定义异常的最佳做法?
What are industry standard best practices for implementing custom exceptions in C#?
我已经检查谷歌和有建议大量,但我不知道哪些容纳更多的可信性。
I have checked Google and there's a great number of recommendations, however I don't know which ones hold more credibility.
如果有人有权威文章的链接,这也将是有益的。
If anybody has any links to authoritative articles, that would also be helpful.
推荐答案
有关创建自定义异常的标准是从的异常。然后,您可以介绍你自己的属性/方法和构造函数重载(如适用)。
The standard for creating custom exceptions is to derive from Exception. You can then introduce your own properties/methods and overloaded constructors (if applicable).
下面是一个自定义 ConnectionFailedException
这需要一个额外的参数,它是特定的异常类型的一个基本的例子。
Here is a basic example of a custom ConnectionFailedException
which takes in an extra parameter which is specific to the type of exception.
[Serializable]
public class ConnectionFailedException : Exception
{
public ConnectionFailedException(string message, string connectionString)
: base(message)
{
ConnectionString = connectionString;
}
public string ConnectionString { get; private set; }
}
在此可以在其中应用程序试图连接到一个数据库例如
In the application this could be used in scenarios where the application is attempting to connect to a database e.g.
try
{
ConnectToDb(AConnString);
}
catch (Exception ex)
{
throw new ConnectionFailedException(ex.Message, AConnString);
}
这是给你,然后办理 ConnectionFailedException
在一个较高的水平(如适用)
It's up to you to then handle the ConnectionFailedException
at a higher level (if applicable)
这篇关于什么是行业标准最好在C#中实现自定义异常的做法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!