自定义异常,没有.NET中的新抛出

时间:2013-05-13 08:11:35

标签: .net exception-handling custom-exceptions

我不确定这是否可能。 (我认为应该)。是否有可能在不抛出新内容的情况下捕获一个客户问题?

        try
        {
            //Some logic which throws exception
        }
        catch (Exception)
        {
            throw new CustomException();
        }

我想拥有的内容如下:

        try
        {
            //Some logic which throws exception
        }
        catch (CustomException)
        {
            // Handles the exception
        }

我已经尝试过以上但是它没有直接捕获我的CustomException。我必须做“throw new CustomException()”并不理想。我做错了什么?

我的自定义异常类如下所示:

 [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 个答案:

答案 0 :(得分:1)

catch子句不会自动转换异常,它不是它的工作方式。它将过滤try子句中抛出的异常。使用

catch (CustomException e)
{
}

您正在处理 CustomException个实例或派生异常clasess的实例 - 换句话说,只有当try块抛出其中任何一个时,才会执行catch子句。因此,如果例如FileNotFoundException被抛出,则catch子句将不会被执行,代码将导致未处理的FileNotFoundException

如果您的目的是让代码仅针对CustomException块中可能发生的所有可能异常抛出try,则需要捕获所有异常。 常规捕获块将为您执行此操作:

catch (Exception e) // catches exceptions of any type
{
    throw new CustomException(e.Message, e);
}

请注意,我们在CustomException构造函数中传递了原始异常(可以选择重复使用消息,您可以自己添加消息)。这是一个经常被忽略但非常重要的实践,因为通过传递内部异常,您将在日志中拥有完整的堆栈跟踪,或者在调试时获得更好的问题信息。