问题
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 { }
回答1:
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.
回答2:
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.
回答3:
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.
回答4:
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.
回答5:
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;
}
来源:https://stackoverflow.com/questions/4692056/is-there-a-situation-when-its-appropriate-to-use-empty-catch-block