0

我不确定这是否可能。(我认为应该)。是否可以在不抛出新异常的情况下捕获自定义异常,如下所示?

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

谢谢,

4

1 回答 1

1

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

catch (CustomException e)
{
}

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

如果您的意图是让您的代码仅CustomException针对块中可能发生的所有可能异常抛出try,您需要捕获所有这些异常。一个通用的 catch 块将为您执行此操作:

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

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

于 2013-05-13T08:26:17.790 回答