捕获非特定异常(例如 System.Exception)是一种不好的

Is this a bad practice to catch a non-specific exception such as System.Exception? Why?(捕获非特定异常(例如 System.Exception)是一种不好的做法吗?为什么?)
本文介绍了捕获非特定异常(例如 System.Exception)是一种不好的做法吗?为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

这篇关于捕获非特定异常(例如 System.Exception)是一种不好的做法吗?为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)