Is there a situation when it's appropriate to

2019-06-15 11:01发布

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

5条回答
劳资没心,怎么记你
2楼-- · 2019-06-15 11:13

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.

查看更多
Summer. ? 凉城
3楼-- · 2019-06-15 11:16

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.

查看更多
我欲成王,谁敢阻挡
4楼-- · 2019-06-15 11:17

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.

查看更多
Fickle 薄情
5楼-- · 2019-06-15 11:20

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;
}
查看更多
唯我独甜
6楼-- · 2019-06-15 11:21

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.

查看更多
登录 后发表回答