Is this a bad practice to catch a non-specific exception such as System.Exception? Why?(捕获非特定异常(例如 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)是一种不好的做法吗?为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:捕获非特定异常(例如 System.Exception)是一种不好的
基础教程推荐
- C# 从 List<List<int>> 中删除重 2022-01-01
- Azure Functions:CosmosDBTrigger 未在 Visual Studio 中触发 2022-01-01
- 当值可以是对象或空数组时反序列化 JSON 2022-01-01
- .NET SerialPort DataReceived 事件未触发 2022-01-01
- 我应该在后面的代码中直接使用 Linq To SQL 还是使 2022-01-01
- 禁止输入少量字符,例如'<'、'&a 2022-01-01
- WPF 模态进度窗口 2022-01-01
- Moq It.Is<>不匹配 2022-01-01
- 如果有人提交恶意软件Nuget包怎么办? 2022-01-01
- 如何使用 .Net 检查 Active Directory 服务器是否已启动并正在运行? 2022-01-01
