如何在一个catch块中捕获所有类型的异常?

use*_*527 4 .net c# web-services exception

catch(Exception ex)
{
    //do what you want here

    //When type of exception is System.Web.Services.Protocols.SoapException
    //if (ex.Code.Name.Equals("Client"))
    //{
    //      msg = "service's function not exist";
    //}
    //else if (ex.Code.Name.Equals("Server"))
    //{
    //     msg = "function error"
    //}
    //else
    //{
    //     msg = "unknown";
    //}
    //MessageBox.Show(msg, "error", MessageBoxButtons.OK);

**But ex is not System.Web.Services.Protocols.SoapException so I cannot call ex.Code.Name.Equals("Client")**


//When System.Net.WebException
//switch (ex.Status)
//{
//   case System.Net.WebExceptionStatus.ConnectFailure:
//              do some thing
                break;
//   case System.Net.WebExceptionStatus.Timeout:
                //do some thing
                break;
//    case System.Net.WebExceptionStatus.ProtocolError:
            switch (((System.Net.HttpWebResponse)ex.Response).StatusCode)
            {
                  case System.Net.HttpStatusCode.NotFound:
                        //do some thing
                        break;
                    case System.Net.HttpStatusCode.ServiceUnavailable:
                        //do some thing
                        break;
                    case System.Net.HttpStatusCode.Unauthorized:
                        //do some thing
                        break;
                    default:
                        //do some thing
                        break;
                }
                break;
            default:
                //do some thing
                break;
        }
}
Run Code Online (Sandbox Code Playgroud)

但是Exception不是System.Net.WebException.所以不能打电话给ex.Status

我的问题:

我有一个Smartclient软件包括WindowsForm作为客户端和Web服务作为服务器.客户端和服务器都是我测试的n层应用程序,发现从客户端调用服务时有任何问题

  1. 在app.config中:service的路径wrrong.我捕获System.NotSupportedException
  2. 或者当服务器无法连接时:System.Net.WebExceptionStatus
  3. 服务器的webconfig错误:System.InvalidOperationException
  4. Service抛出异常:System.Web.Services.Protocols.SoapException ...

我的想法

我调用Exception,作为所有其他异常类型的代表representativeAlException 我有命名空间:Common和两个classese representativeAlException.csBusinessExceptionHandler.cs

使用param作为一个公共函数(representativeAlException ex)

            try
            {
                Err_LogCheck.Service1.Service1 service = new Err_LogCheck.Service1.Service1();
                return service.getDeviceByZero(ZERO);
            }
            catch (Common.representativeAlException ex)
            {
                Common.BusinessExceptionHandler.ProcessException(ex);
            }
Run Code Online (Sandbox Code Playgroud)

我想做的事

服务的地方.只有一个catch块可以处理所有类型的Exception

ProcessException(representativeAlException ex)函数中

switch (ex)
{
case System.InvalidOperationException:
 //Do some thing
 break;
case System.NotSupportedException:
 //Do some thing
 break;
case System.Web.Services.Protocols.SoapException:
 //do some thing
 break;
...
...
Run Code Online (Sandbox Code Playgroud)

dpp*_*dpp 13

要处理所有异常,请使用Exception类.

try
{

}
catch(Exception ex)
{
     switch (ex.GetType().ToString())
     {
         case "System.InvalidOperationException":
              //cast ex to specific type of exception to use it's properties
              ((InvalidOperationException)ex).SomeMethod();
         break;
         case "System.NotSupportedException":
             ((System.NotSupportedException)ex).AnotherMethod();
         break;
         case "System.Web.Services.Protocols.SoapException":
             ((System.Web.Services.Protocols.SoapException)ex).OtherMethod();
         break;
     }

}
Run Code Online (Sandbox Code Playgroud)

为什么你不能只使用多个catch块?

  • 你的问题不明确所以我假设你想要处理所有类型的异常.我正在努力帮助,但我得到的只是投票. (2认同)

Maa*_*ark 10

现在这已成为一项语言功能。只需使用 switch/case 语句

提问者的第一次尝试(在问题的代码片段中注释掉)现在是最简单的,在我看来也是最好的方法。

实际上,我在试图弄清楚 Resharper 对其建议的改进之一做了什么时遇到了这个问题。我仍然不是 100% 确定所涉及的术语,因为我能找到的唯一文档是解释Discards,并且仅在传递正在执行的“与 is 和 switch 关键字匹配的模式”时提到。

正如 Onkel-j 所建议的那样,我从一系列“如果 ex 是类型”开始:

try
{
    doWork();
}
catch (Exception ex)
{
    if (ex is SpecificExceptionType)
    {
        //todo
    }
    else 
    {
        //etc
    }
}
Run Code Online (Sandbox Code Playgroud)

但 resharper 建议我让它将其更改为开关/案例:

try
{
    doWork();
}
catch (Exception ex)
{
    switch (ex)
    {
        case SpecificExceptionType _:
            //todo
            break;            
        default:
            //etc
            break;
    }
}
Run Code Online (Sandbox Code Playgroud)

Resharper 使用Discards来执行某种自动 操作并丢弃未使用的变量。如果您需要实际使用异常作为特定类型,请为其指定一个名称来代替下划线:

try
{
    doWork();
}
catch (Exception ex)
{
    switch (ex)
    {
        case SpecificExceptionType specific:
            HandleSpecificException(specific);
            break;            
        default:
            //etc
            break;
    }
}
Run Code Online (Sandbox Code Playgroud)

或者回答原来的问题:

catch(Exception ex)
{
    //do what you want here
    
    switch(ex)
    {
        case System.Web.Services.Protocols.SoapException soapEx:        
            if (soapEx.Code.Name.Equals("Client"))
            {
                  msg = "service's function not exist";
            }
            else if (soapEx.Code.Name.Equals("Server"))
            {
                 msg = "function error"
            }
            else
            {
                 msg = "unknown";
            }
            MessageBox.Show(msg, "error", MessageBoxButtons.OK);    
            break;
        case System.Net.WebException webEx:
            switch (webEx.Status)
            {
               case System.Net.WebExceptionStatus.ConnectFailure:
                    //do some thing
                    break;
               case System.Net.WebExceptionStatus.Timeout:
                    //do some thing
                    break;
                case System.Net.WebExceptionStatus.ProtocolError:
                    switch (((System.Net.HttpWebResponse)webEx.Response).StatusCode)
                    {
                        case System.Net.HttpStatusCode.NotFound:
                            //do some thing
                            break;
                        case System.Net.HttpStatusCode.ServiceUnavailable:
                            //do some thing
                            break;
                        case System.Net.HttpStatusCode.Unauthorized:
                            //do some thing
                            break;
                        default:
                            //do some thing
                            break;
                    }
                    break;
                default:
                    //do some thing
                    break;
            }
            break;
        default:
            //etc
            break;
    }
}
Run Code Online (Sandbox Code Playgroud)


Onk*_*l-j 5

User2808350是正确的,try catch 块出于某种原因可以有许多不同的捕获,但是有时您会发现使用此模式时正在重复自己(DRY)。

可以生成简洁、可读代码的另一种方法是使用is运算符,如果您的异常是特定类型的实例或从该类型派生的实例,则该运算符的计算结果为 true。不幸的是,无法在 switch 块中使用is运算符,因此您必须使用 if-then-else。

这是我测试异常类型并相应设置退出代码的示例。

try
{
    // try something
}
catch (Exception e)
{
    if (e is FileNotFoundException)
        Environment.ExitCode = 2;
    else if (e is InvalidOperationException)
        Environment.ExitCode = 1;
    else
        Environment.ExitCode = 42;
    throw;
}
Run Code Online (Sandbox Code Playgroud)