2013-05-13 19 views
0

我不确定这是否可能。 (我认为它应该)。如果不按照以下方式抛出新的产品,是否有可能抓住客户的观点?在.NET中没有新投入的自定义异常

 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

问题是什么?你的第二个代码片段看起来很好。 – dlev 2013-05-13 08:13:25

+0

对不起,只是编辑我的问题。 – daehaai 2013-05-13 08:14:54

+1

代码是否抛出CustomException?或者是抛出一个不同的异常,你想变成一个CustomException?如果是后者,那么第二种方法就行不通了。 – dlev 2013-05-13 08:16:12

回答

1

catch条款不会自动转换例外,这不是它的工作方式。它将过滤器try子句中引发的异常。通过使用

catch (CustomException e) 
{ 
} 

你正在处理CustomException实例或派生的异常clasess的实例 - 换句话说,只有当try块抛出任何这些的catch子句就会执行。因此,如果例如FileNotFoundException被抛出,您的catch子句将不会被执行,并且代码将导致未处理的FileNotFoundException

如果您的意图是让您的代码仅丢失CustomException,以避免try块中可能出现的所有可能的异常情况,则需要捕获所有这些异常。一个一般catch块会为你做这个:

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

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