开发者

Is there a situation when it's appropriate to use empty catch block? [duplicate]

开发者 https://www.devze.com 2023-02-04 01:09 出处:网络
This question already has answers here: Closed 12 years ago. Possible Duplicates: Why are empty catch blocks a bad idea?
This question already has answers here: Closed 12 years ago.

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 { }


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:

Usually empty try-catch is a bad idea because you are silently swallowing an error condition and then continuing execution. Occasionally this may be the right thing to do, but often it's a sign that a developer saw an exception, didn't know what to do about it, and so used an empty catch to silence the problem.

It's the programming equivalent of putting black tape over an engine warning light.


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.


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.


Axiom:

Empty catch blocks are absolute evil

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.


I used it for some self-written libraries where i need some kind of bool TrySomething(out object) function or object TrySomething() where the underlying call doesn't provide any other mechanism as an exception. In this case i use an empty catch block and return false or null (depending on the function signature).

Example to prove empty catch block

public bool TrySomething(out object destination)
{
    try
    {
        destination = DoSomething();
        return true;
    }
    catch
    {}

    return false;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消