【问题标题】:.NET Custom Exception not being caught where expected.NET 自定义异常没有在预期的地方被捕获
【发布时间】:2012-09-25 01:21:08
【问题描述】:

这感觉像是一个愚蠢的问题,但我有一个控制台应用程序应该抛出和处理自定义异常类型。由于某种原因,它陷入了一般的异常捕获,我不确定为什么。

主程序:

try
{
    result = MyService.ExecuteSearch(paramItems);
}
catch (TimeoutException ex)
{
    // Catch time out exceptions here
}
catch (SearchAnticipatedException ex)
{
    // THIS IS WHERE I WANT TO BE WITH MY CUSTOM EXCEPTION & MESSAGE
}
catch (Exception ex)
{
    // THE ORIGINAL EXCEPTION IS BEING CAUGHT HERE 
}

我的逻辑的主要内容捕获了一个 EndpointNotFoundException,我试图而不是抛出那个 - 用更有意义的消息(和其他信息)抛出我的自定义异常。但原来的 endpoingnotfoundexception 正在那个 Catch (Exception ex) 块中处理。

 try
 {
          // do some logic
          ((IClientChannel)proxy).Close();
 }
 catch (CommunicationObjectFaultedException ex)
 {
      throw new SearchAnticipatedException(ServiceState.Critical, hostName, ex);
 }
 catch (EndpointNotFoundException ex)
 {
      throw new SearchAnticipatedException(ServiceState.Critical, hostName, ex);
 }
 finally
 {
    if (((IClientChannel)proxy).State == CommunicationState.Opened)
    {
         factory.Abort();
         ((IClientChannel)proxy).Close();
    }
 }

如果我注释掉主要部分底部的一般异常,那么它会被正确的块捕获 - 我认为它会首先被更具体的异常捕获,如果它与其中任何一个都不匹配,它会属于最后一种一般类型的块。

希望这只是我塞满的小东西:)

我的异常类看起来像:

 class SearchAnticipatedException : System.Exception
    {
        public int ServiceStateCode { get; set; }

        public SearchAnticipatedException(MyService.ServiceState serviceState, string message, Exception innerException)
            : base(message, innerException)
        {
            ServiceStateCode = (int)serviceState;
        }

        public static string FormatExceptionMessage(string message, MyService.ServiceState serviceState)
        {
            return serviceState.ToString().ToUpper() + SearchResult.CODE_MESSAGE_DELIMITER + message;
        }

    }

【问题讨论】:

    标签: .net exception-handling


    【解决方案1】:

    我不确定,因为我认为第一个匹配的 catch 子句会优先,但如果你这样做,你可能会更成功:

    try 
    { 
       ...
    }
    catch(Exception ex)
    {
         if (ex is TimeoutException)
         {
            ...
         }
         else if (ex is SearchAnticipatedException)
         {
            ...
         }
         else
         {
             ...
         }
    }
    finally
    {
    }
    

    【讨论】:

    • 谢谢 - 发现这是在 finally 块中引发的另一个异常。我认为如果标准异常处理没有启动,就会发生一些愚蠢的事情:)
    【解决方案2】:

    想通了 - 事实证明,如果存在 endpointNoutFoundException,那么我无法检查通道的状态。 IE。如果它是打开的,我想关闭它。它在 finally 块中抛出异常:)

    我只是要调用 factory.abort()。

    finally
    {
       factory.Abort();
    }
    

    当我设置超时值时,我想确保如果发生超时异常,那么任何连接都会正确关闭。

    【讨论】:

    • 所以让我说清楚。在发布正确的异常未被捕获之前,您没有验证引发了什么异常。
    • 不管发生了什么,我都希望 finally 清理所有可能打开的连接。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-21
    • 1970-01-01
    相关资源
    最近更新 更多