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

发布于 2024-10-14 07:07:05 字数 94 浏览 2 评论 0原文

在 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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

|煩躁 2024-10-21 07:07:05

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

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

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

    public string ConnectionString { get; private set; }
}

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

try
{
    ConnectToDb(AConnString);
}
catch (Exception ex)
{
    throw new ConnectionFailedException(ex.Message, AConnString);
}

您可以在更高级别处理 ConnectionFailedException (如果适用)。

另请参阅 < a href="http://msdn.microsoft.com/en-us/library/vstudio/ms229064%28v=vs.100%29.aspx" rel="noreferrer">设计自定义异常 和 自定义例外

The standard for creating custom exceptions is to derive from Exception. You can then introduce your own properties/methods and overloaded constructors (if applicable).

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);
}

It's up to you to then handle the ConnectionFailedException at a higher level (if applicable)

Also have a look at Designing Custom Exceptions and Custom Exceptions

春花秋月 2024-10-21 07:07:05

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

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) { }
    }
}

另请参阅:http:// www.capprime.com/software_development_weblog/2005/06/16/CreatingACustomExceptionClassInC.aspx

Here is the code to create a custom exception:

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) { }
    }
}

See also: http://www.capprime.com/software_development_weblog/2005/06/16/CreatingACustomExceptionClassInC.aspx

落日海湾 2024-10-21 07:07:05

我假设您正在寻找异常处理实践。因此,请查看以下文章,

http://msdn.microsoft.com/en -us/library/ms229014.aspx //给出有关异常的总体思路,包括自定义异常

I assume you are looking for exception handling practices. So have look on following articles,

http://msdn.microsoft.com/en-us/library/ms229014.aspx //gives overall ideas about exceptions including custom exceptions

记忆之渊 2024-10-21 07:07:05

我使用自定义异常来传达错误的性质。

例如,我喜欢使用框架提供的“ArgumentNullException”来检查参数。然后,当我在调试器或错误日志中看到此错误时,我立即知道错误的性质,而无需进一步阅读。

范围的另一端是 InvalidOperationException,它几乎可以意味着任何事情。

自定义异常的替代方法是详细的错误消息。没关系,但是通过创建 ConnectionFailed 等自定义异常更有意义。然后消息本身可以提供更多详细信息。

创建此类自定义异常时,我不添加任何新属性。这样做的原因是,如果您有一个错误记录器,您希望它能够处理所有异常。如果您添加特殊属性,则错误记录器将忽略它。例如,如果您使用 MSTest,当您运行测试但失败时,不会显示自定义属性。但如果您坚持使用基类的 Message 属性,它将显示得很好。

所以子类化非常简单:

public class NavigationException : Exception{
    public NavigationException() {}
    public NavigationException(string msg) : base(msg) {}
    public NavigationException(string msg, Exception inner) : base(msg, inner) {}
}

这非常简单,适用于任何错误记录器,当我看到它时,我知道这是一个导航问题,如果需要,我可以查看详细信息。

格雷格

I use Custom Exceptions to communicate the nature of the error.

For example, I like using the framework provided "ArgumentNullException" to check arguments. Then later, when I see this error either in the debugger, or in an error log, I immediately know the nature of the error without reading any further.

The other end of the spectrum is the InvalidOperationException which could mean pretty much anything.

The alternative to custom exceptions is detailed error messages. That's ok, but by making a custom exception such as ConnectionFailed is more meaningful. Then the message itself can give greater details.

When creating such custom exceptions, I do not add any new properties. The reason for this is that if you have an error logger, you want it to work on all exceptions. If you add a special property, then the error logger is going to ignore it. For example, if you use MSTest, when you run your test and it fails, the custom properties are not displayed. But if you stick with the Message property of the baseclass, it will display just fine.

So the subclassing is very simple:

public class NavigationException : Exception{
    public NavigationException() {}
    public NavigationException(string msg) : base(msg) {}
    public NavigationException(string msg, Exception inner) : base(msg, inner) {}
}

This is very straightforward, works with any error logger, and when I see it, I know it was a Navigation problem and I can view the details if needed.

Greg

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文