是否存在适合使用空 catch 块的情况?
你知道在什么情况下空 catch 块并不是绝对的邪恶吗?
try
{
...
// What and When?
...
}
catch { }
Possible Duplicates:
Why are empty catch blocks a bad idea?
Is there any valid reason to ever ignore a caught exception
Do you know any situations when an empty catch block is not the absolute evil?
try
{
...
// What and When?
...
}
catch { }
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
这方面有很多问题,尝试看看:
为什么空的 catch 阻止了一个坏主意?
从该帖子接受的答案:
There are a lot of questions on this, try to look at:
Why are empty catch blocks a bad idea?
From that post's accepted answer:
我想说,您至少应该提供某种评论或记录的消息,表明您在 try {} 中放入的内容引发了异常,这就是您不执行任何操作的原因。
I would say you should at least be providing some sort of comment or logged message indicating that what you put in the try {} threw an exception and this is why you aren't doing anything.
看看这个,它基本上将您可能遇到的异常类型分为四类,其中任何一类都不应该由空的 catch 块处理。
Take a look at this, it basically breaks down the kind of exceptions you could encounter into four categories, none of which should be handled by an empty catch block.
公理:
不要试图找到解决这个问题的方法。仅仅试图找到它们不是绝对邪恶的案例就意味着你正在浪费宝贵的大脑周期。不要试图在这里找到模式,想着“嗯,我应该在这里放置一个空的 catch 块吗?”
如果您在某人的代码中偶然发现了一个空的 catch 块,那么您就偶然发现了技术债务。修复它。即使只是在空的 catch 块中添加一条日志记录语句,您也会让这个世界变得更美好。
Axiom:
Don't try to find your way around this. Just by trying to find cases where they aren't absolute evil means you're wasting precious brain cycles. Don't try to find a pattern here, thinking "hmm, should I put an empty catch block here?"
If you stumble upon an empty catch block in somebody's code, you've just stumbled upon technical debt. Fix it. Even just by adding one logging statement inside an empty catch block, you'll make this world a better place.
我将它用于一些自写的库,其中我需要某种
bool TrySomething(out object)
函数或object TrySomething()
,其中底层调用不提供任何其他机制除外。在本例中,我使用空的 catch 块并返回false
或null
(取决于函数签名)。证明空 catch 块的示例
I used it for some self-written libraries where i need some kind of
bool TrySomething(out object)
function orobject TrySomething()
where the underlying call doesn't provide any other mechanism as an exception. In this case i use an empty catch block and returnfalse
ornull
(depending on the function signature).Example to prove empty catch block