用户登录
用户注册

分享至

捕获非特定异常(例如 System.Exception)是一种不好的做法吗?为什么?

  • 作者: 人间哪有真情在4764797
  • 来源: 51数据库
  • 2023-02-08

问题描述

我目前正在进行代码审查,下面的代码让我大吃一惊.我看到此代码存在多个问题.你是否同意我的观点?如果是这样,我该如何向我的同事解释这是错误的(固执的类型......)?

I am currently doing a code review and the following code made me jump. I see multiple issues with this code. Do you agree with me? If so, how do I explain to my colleague that this is wrong (stubborn type...)?

  • 捕获一个通用异常(Exception ex)
  • 使用if (ex is something)"代替另一个 catch 块
  • 我们吃SoapException、HttpException 和WebException.但是,如果 Web 服务失败了,就没有什么可做的了.

代码:

try
{
    // Call to a WebService
}
catch (Exception ex)
{
    if (ex is SoapException || ex is HttpException || ex is WebException)
    {
        // Log Error and eat it.
    }
    else
    {
        throw;
    }
}

推荐答案

口头禅是:

  • 您应该只在以下情况下捕获异常你可以妥善处理它们

因此:

  • 你不应该抓住一般例外.

在您的情况下,是的,您应该只捕获这些异常并做一些有用的事情(可能不仅仅是吃掉它们——您可以在记录它们之后throw).

In your case, yes, you should just catch those exceptions and do something helpful (probably not just eat them--you could throw after you log them).

您的编码器正在使用 throw(不是 throw ex),这是 .

Your coder is using throw (not throw ex) which is good.

这是您可以捕获多个特定异常的方法:

This is how you can catch multiple, specific exceptions:

try
{
    // Call to a WebService
}
catch (SoapException ex)
{
    // Log Error and eat it
}
catch (HttpException ex)
{
    // Log Error and eat it
}
catch (WebException ex)
{
    // Log Error and eat it
}

这几乎等同于您的代码所做的.您的开发人员可能这样做是为了避免重复记录错误并吃掉它"块.

This is pretty much equivalent to what your code does. Your dev probably did it that way to avoid duplicating the "log error and eat it" blocks.

软件
前端设计
程序设计
Java相关