65.9K
CodeProject 正在变化。 阅读更多。
Home

C#.NET 中的自定义异常

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.77/5 (28投票s)

2010 年 7 月 5 日

CPOL
viewsIcon

216126

在开发过程中,我总是寻找实现目标的最优和高效方法。上次,我找到了一种方法来记录异常以及抛出异常的方法参数。通常,对于大型项目(即,具有多个模块相互通信的项目),应该定义自定义异常。定义自定义异常类:
[Serializable]
public class CustomException : Exception
{
    public CustomException()
        : base() { }
    
    public CustomException(string message)
        : base(message) { }
    
    public CustomException(string format, params object[] args)
        : base(string.Format(format, args)) { }
    
    public CustomException(string message, Exception innerException)
        : base(message, innerException) { }
    
    public CustomException(string format, Exception innerException, params object[] args)
        : base(string.Format(format, args), innerException) { }
    
    protected CustomException(SerializationInfo info, StreamingContext context)
        : base(info, context) { }
}
示例: 1. 不带消息抛出异常
throw new CustomException()
2. 抛出带有简单消息的异常
throw new CustomException(message)
3. 抛出带有消息格式和参数的异常
throw new CustomException("Exception with parameter value '{0}'", param)
4. 抛出带有简单消息和内部异常的异常
throw new CustomException(message, innerException)
5. 抛出带有消息格式和内部异常的异常。请注意,可变长度参数始终是浮动的。
throw new CustomException("Exception with parameter value '{0}'", innerException, param)
6. 最后一个自定义异常构造函数是在异常序列化/反序列化期间使用的。
© . All rights reserved.