在C#中实现自定义异常的行业标准最佳实践是什么?
我在谷歌上查过,有很多推荐,但我不知道哪一个更可信。
如果任何人有任何权威文章的链接,那也会很有帮助。
发布于 2011-01-25 18:09:49
创建自定义异常的标准是从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 (如果适用)
还可以了解一下Designing Custom Exceptions和Custom Exceptions
发布于 2012-08-14 23:20:19
下面是创建自定义异常的代码:
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
发布于 2011-01-25 17:48:10
我假设您正在寻找异常处理实践。所以请看下面的文章,
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 //
https://stackoverflow.com/questions/4791823
复制相似问题