在C#中实现自定义异常的行业标准最佳实践是什么?

Dar*_*ung 67 c# custom-exceptions

在C#中实现自定义异常的行业标准最佳实践是什么?

我检查了谷歌,并提出了大量建议,但我不知道哪些建议具有更高的可信度.

如果任何人有权威文章的链接,那也会有所帮助.

Jam*_*mes 68

创建自定义异常的标准是从Exception派生.然后,您可以引入自己的属性/方法和重载的构造函数(如果适用).

这是一个自定义的基本示例,ConnectionFailedException它接受一个特定于异常类型的额外参数.

[Serializable]
public class ConnectionFailedException : Exception
{
    public ConnectionFailedException(string message, string connectionString)
        : base(message)
    {
        ConnectionString = connectionString;
    }

    public string ConnectionString { get; private set; }
}
Run Code Online (Sandbox Code Playgroud)

在应用程序中,这可以在应用程序尝试连接到数据库的情况下使用,例如

try
{
    ConnectToDb(AConnString);
}
catch (Exception ex)
{
    throw new ConnectionFailedException(ex.Message, AConnString);
}
Run Code Online (Sandbox Code Playgroud)

然后由您来处理ConnectionFailedException更高级别(如果适用)

另请参阅设计自定义例外自定义例外


Mic*_*dox 9

以下是创建自定义异常的代码:

using System;
using System.Runtime.Serialization;

namespace YourNamespaceHere
{
    [Serializable()]
    public class YourCustomException : Exception, ISerializable
    {
        public YourCustomException() : base() { }
        public YourCustomException(string message) : base(message) { }
        public YourCustomException(string message, System.Exception inner) : base(message, inner) { }
        public YourCustomException(SerializationInfo info, StreamingContext context) : base(info, context) { }
    }
}
Run Code Online (Sandbox Code Playgroud)

另见:http://www.capprime.com/software_development_weblog/2005/06/16/CreatingACustomExceptionClassInC.aspx

  • FWIW - 这几乎正是使用 Visual Studio 中包含的“Exception”片段所产生的结果。 (2认同)

par*_*agy 8

我假设您正在寻找异常处理实践.那么请看下面的文章,

http://msdn.microsoft.com/en-us/library/ms229014.aspx //提供有关异常的整体提示,包括自定义异常

http://blogs.msdn.com/b/jaredpar/archive/2008/10/20/custom-exceptions-when-should-you-create-them.aspx //