5 ms·
I think the main point here is to avoid general catches and instead catch specific exceptions. The author raises the interesting point that if it's truly an ex
by sherwin 13y ago
I think the main point here is to avoid general catches and instead catch specific exceptions.
The author raises the interesting point that if it's truly an exception, you're better off letting the system crash all together (especially in a webapp, where you're basically dropping a single request for a single user) -- and if it's an "expected exception", then you should be handling it directly.
I don't see how that reduces to "never use try/catch" though, since catching a specific exception (or types of exceptions) is a way of "handling it directly."
- cleaver 13y agoUnfortunately, "Don't do X" is better click bait than "You should think carefully when you want to do X". There will be cases where you want to do "catch {}" — you don't always have control over the exceptions thrown by a lower-level library. It might be good to create a standard where you log them conditionally, or something that could aid in troubleshooting.
- joshribakoff 13y agoYes, in my front controller I wanted to log to the filesystem & email exceptions. The email library threw it's own exceptions, which I wanted to ignore with "catch {}"... if email was down, and I already logged the exception, there's nothing left to do.
- V-2 13y agoTrue, but as a developer, I expect a comment inside your empty catch block telling me why it is justified. I can't remember ever seeing one...
- JasonFruit 13y agoOddly, I have seldom seen an empty catch {} without a comment, though often it was simply to point out that, yes, this is intentional. Even that is better than leaving me wondering if the code is just unfinished.
- deathanatos 13y agoNot only are the points you raise valid, but I feel the webapp example exemplifies the strengths of exceptions: That the default behavior is to propagate to a context that can deal with the exception, and that you can catch them all at strategic points, like the main request handler of a webserver. You're not "crashing the thread" like the article implies: you're purposefully catching some error you didn't expect (bugs happen), logging/capturing it for debugging (perhaps even with a traceback), and gracefully returning at worst a 500 to the current request, all the while continuing to serve further requests. It's been best practice for quite some time not to catch { // heh heh he. }.