从异常中获取异常类型

时间:2014-07-16 05:21:31

标签: c#

我有一个应用程序将SAP与RFC调用连接起来,我需要在连接失败时向用户显示通知,同时尝试与SAP建立RFC调用。而且我得到以下例外。

{
    SAP.Middleware.Connector.RfcCommunicationException: 
    LOCATION    CPIC (TCP/IP) on local host with Unicode
    ERROR       partner '151.9.39.8:8010' not reached
    TIME        Wed Jul 16 10:32:05 2014
    RELEASE     720
    COMPONENT   NI (network interface)
    VERSION     40
    RC          -10
    MODULE      nixxi.cpp
    LINE        3286
    DETAIL      NiPConnect2: 151.9.39.8:8010
    SYSTEM CALL connect
    ERRNO       10060
    ERRNO TEXT  WSAETIMEDOUT: Connection timed out
    COUNTER     2
} 

通过使用此异常,我需要通知用户。但是我怎样才能确定它是否是SAP.Middleware.Connector.RfcCommunicationException,因为我也在处理其他异常。有没有办法在不连接上述异常字符串的情况下获取异常类型。

在我的try catch块中 我目前正在这样做,但它没有用。

catch (Exception ex)
{  
    if (ex.ToString().ToLower() == "rfccommunicationexception")
    {
        MessageError = "RFC error";
    }
}

4 个答案:

答案 0 :(得分:6)

明确捕获异常:

catch(SAP.Middleware.Connector.RfcCommunicationException)
{
    // RFC exception
}
catch(Exception e)
{
    // All other exceptions
} 

答案 1 :(得分:3)

最好的方法是拥有多个catch块:

try
{
   // your code
}
catch(RfcCommunicationException rfcEx)
{
  // handle rfc communication exception
}
cathc(Exception ex)
{
  // handle other exception
}

答案 2 :(得分:2)

您可以使用is

例如: -

catch (Exception exception )
{  
    if (exception is SAP.Middleware.Connector.RfcCommunicationException)
    { 
       ////Your code
    }
}

或者正如Resharper建议更好地捕捉特定异常,如下所示: -

catch(SAP.Middleware.Connector.RfcCommunicationException)
{
    // Your code    
}

答案 3 :(得分:1)

你可以尝试这个:

// Catch the exception
catch(exception e)
{
    // Check if the type of the exception is an RFC exception.
    if(e is SAP.Middleware.Connector.RfcCommunicationException)
    {

    }
    else // It is not an RFC exception.
    {

    }
}

或者您可以单独尝试catch每个例外,如下所示:

catch(SAP.Middleware.Connector.RfcCommunicationException exception)
{

}
catch(exception e)
{

}