Re:Don’t Use Try/Catch (2010)
by sherwin on Saturday December 28, 2013 @12:14PM
(#6975422)
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."
Re:Don’t Use Try/Catch (2010)
by cleaver on Saturday December 28, 2013 @12:43PM
(#6975527)
Unfortunately, "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.
Re:Don’t Use Try/Catch (2010)
by JasonFruit on Saturday December 28, 2013 @01:33PM
(#6975697)
Oddly, 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.
Re:Don’t Use Try/Catch (2010)
by joshribakoff on Saturday December 28, 2013 @12:49PM
(#6975552)
Yes, 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.
Re:Don’t Use Try/Catch (2010)
by deathanatos on Saturday December 28, 2013 @12:54PM
(#6975568)
Not 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. }.
Re:Don’t Use Try/Catch (2010)
by alexRohde on Saturday December 28, 2013 @01:58PM
(#6975817)
I cannot believe this got on the front page. Structured exception handling is crucial for atomicity and building robust systems.
Nothing about catch requires the program to continue executing as though no exception ever happened, many catches can be fatal but handle emergency cleanup.
Re:Don’t Use Try/Catch (2010)
by Locke1689 on Saturday December 28, 2013 @01:02PM
(#6975599)
On Windows you may even want to let the application crash.
If an application crashes on Windows due to an exception, it can be picked up by Microsoft's Watson error logging (now called Windows Error Reporting, I believe). If the user has marked the checkbox "help Microsoft improve Windows by sending crash information" then the dump of the application will be sent to a central location, where it can be triaged and accessed by the application's developer.
Now instead of just a generic entry in a log file, you have a full memory dump of the exception.
Re:Don’t Use Try/Catch (2010)
by gweinberg on Saturday December 28, 2013 @01:30PM
(#6975680)
I used to use try/catch with an empty catch block in Java all the time. The exception could never in fact occur, but the compiler required me to either add a catch block or declare that my function raises an exception, when it fact it doesn't.
Yes, I did include a "this never happens" comment. That is my favorite comment, but only if it is true.
Re:Don’t Use Try/Catch (2010)
by wheaties on Saturday December 28, 2013 @01:37PM
(#6975711)
Ah, it was people like you who did this even when, as you said it should never happen, that caused me many a late night... 'cause it did and that empty catch block hid it.
Don't leave empty catch blocks. At least put in some form of logging of the exception, just in case.
Re:Don’t Use Try/Catch (2010)
by alecdbrooks on Saturday December 28, 2013 @01:46PM
(#6975743)
My thought would be to add an assertion that always fails inside the catch block, but this probably only makes sense if you use assertions already, as they have to be turned on explicitly in Java.
Re:Don’t Use Try/Catch (2010)
by buerkle on Saturday December 28, 2013 @01:47PM
(#6975746)
Years ago I found the source of my troubles which took longer than it should have because Tomcat had an empty catch around InterruptedException with a "this will never happen" comment.
Re:Don’t Use Try/Catch (2010)
by Aqueous on Saturday December 28, 2013 @12:49PM
(#6975548)
The problem is sometimes you need to be able to report an exception elsewhere than the global log file , for example fold the exception into a user response. For a web application, for instance, using ANORM/Scala/Play, you might have a unique key constraint that throws an exception when it's violated. I need to be able to use that to emit a JSON response to the user telling them there is already a file with that name, extension combination etc. So I have to catch the exception in my controller in order to properly report that to the user.
The author is right that your code needs to properly react to exceptions and not swallo them. . A global exception handler lets you report to all exceptions, but in order to give proper feedback to the user you definitely have to catch exceptions elsewhere in the code.
Re:Don’t Use Try/Catch (2010)
by __derek__ on Monday December 30, 2013 @07:25PM
(#6988113)
Or use exceptions to write cleaner code: http://www.jeffknupp.com/blog/2013/02/06/write-cleaner-pytho.... That post is specific to Python, which actually implements a lot of internal features using try-except, but it suffices as an argument against the idea that catching exceptions is itself a bad practice.
Re:Don’t Use Try/Catch (2010)
by Bahamut on Saturday December 28, 2013 @12:18PM
(#6975442)
From the frontend perspective, isn't it sometimes ideal to use try/catch? Unfortunately with the fragmented browser implementations of HTML5 and JavaScript, sometimes what is an exception in one browser is correct usage in another. It's a complex beast of a problem at times.
Of course, you should be judicious in your usage of try/catch, since it's obviously something that can be abused very poorly.
Re:Don’t Use Try/Catch (2010)
by jakub_g on Saturday December 28, 2013 @03:24PM
(#6976339)
Due to asynchronous nature of JavaScript it's basically impossible to use "one big try/catch". Code that is invoked via setTimeout executes with an empty stack so something like
try { setTimeout(foo, 1000) } catch (ex) { ... }
won't be caught here if foo throws. In some DOM APIs there are 'onerror' handlers (like XHR), in NodeJS the convention is to have an "error" first parameter in the callback (which is null if there's no error).
Also try-catch generates additional scope object inside the catch clause hence it's a bit more expensive than just doing a function call.
Generally try-catch makes sense in JavaScript only locally when executing some external synchronous code that is known to throw exceptions.
Re:Don’t Use Try/Catch (2010)
by potatolicious on Saturday December 28, 2013 @12:26PM
(#6975470)
Unfortunately yeah - sometimes the brokenness of tr/catch you inherit from the platform level.
Reminds me of when I was trying to write a Win8/Metro app for fun. Turns out in the particular network class I was using 404's throw exceptions. What a horrific design - 404 isn't an unexpected state at all, particularly when calling restful apis. But there we were, a pointless try/catch or nothing.
A lot of the brokenness with exceptions is software that models expected operational state as exceptions.
Re:Don’t Use Try/Catch (2010)
by windowsworkstoo on Saturday December 28, 2013 @04:29PM
(#6976700)
Yes that was an issue with the old WebRequest classes, but now with System.Net.Http the situation is much better (though they did what most people end up doing and wrapping WebRequest in a sensible manner)
Re:Don’t Use Try/Catch (2010)
by V-2 on Saturday December 28, 2013 @12:56PM
(#6975578)
I'd go one step further - throw your own exceptions whenever you can. Just put assertions in your code. Even verbose assertions. Which error report would you rather receive - "foo was set to null while file was still open!", or a generic "NullReferenceException" caught two stack frames away. If it crashes, it crashes anyway. After that it is only about how fast you can fix the bug.
Re:Don’t Use Try/Catch (2010)
by MaulingMonkey on Saturday December 28, 2013 @04:34PM
(#6976718)
Please use some restraint! Sometimes an exception is not the answer!
I've had... I think it was Windows::UI::Input::PointerPoint::GetCurrentPoint throw exceptions if the finger passed in was no longer touching the screen. Sounds fine at first, right? Except...
1) This occurred before "finger released" events, so you'd run into a crash because they thought throwing an exception was better than returning the last known finger position, which would've rightly left me with no error report.
2) This occurred in a nasty rare corner case, making figuring out the reproduction a PITA. I don't think I'm alone in not expecting such a simple function to throw when given a known-to-me-valid fingerId. Worse, the exception was completely undocumented on MSDN -- either explicitly or as a hint from function signature (at least Win32 had the common decency to return BOOL or HRESULT.)
3) I found no method for validating a finger ID, so one had to simply catch the exception and accept the massive framerate dip of exception handling overhead if the user pawed at the screen. Before you mistake that for hyperbolic performance concerns: I could make a smooth 30fps tank to bellow 10fps consistently. I measured!
Touch input isn't the only unexpected thing throwing exceptions for WinRT. The end result of this "throw exceptions whenever you can" mentality is I've been forced to build a habit of wrapping every WinRT API call in extremely wide try/catch blocks to log whatever random undocumented exceptions come crawling out of it. By becoming the rule, it took the "exception" out of "exceptions". I'm sure you'll agree: This is horrifically ugly, slow, and in generally poor taste.
But it's necessary. The other alternative is you hopefully find as many as 90% of the weird junk that crashes your program with exceptions, most of which you don't actually care about in the slightest -- and the other 10% avoid discovery and instead explode your stuff in production, most of which will be for no good reason.
Re:Don’t Use Try/Catch (2010)
by V-2 on Sunday December 29, 2013 @09:47PM
(#6982742)
Of course sometimes exceptions are not the answer... I don't mean one should "throw them whenever they can" in literal sense, like the more the merrier :)
Exceptions, as the name itself indicates, should only be reactions to EXCEPTIONAL situations. Showstoppers.
The adage is: don't use exceptions for flow control. In the case you described, it seems to me that they did just that, and I don't condone that. It's clearly a case of bad, or at least unfortunate API design...
By "whenever you can" I meant "whenever you can once the ground criteria are met", I kind of thought it goes without saying but I should've been more precise
Re:Don’t Use Try/Catch (2010)
by drdaeman on Saturday December 28, 2013 @01:02PM
(#6975603)
Please, don't even think about such approach if you handle many long-living tasks (like, say, client connections) in a single OS-level unit of execution (process or thread) and the error/exception happens for a single task but crashes the whole stack.
Re:Don’t Use Try/Catch (2010)
by V-2 on Sunday December 29, 2013 @09:48PM
(#6982745)
Just make sure they are caught and handled. Your single task should not allow any exceptions to bubble up all the way to the whole stack. Whether they are your own or not.
Re:Don’t Use Try/Catch (2010)
by joshribakoff on Saturday December 28, 2013 @12:16PM
(#6975434)
I absolutely agree. Magento does this & its one of the reasons why it sucks. They catch an exception, and throw a new one. Basically eating the message & stack trace. Then that one in turn gets caught and a 3rd new exception is thrown, eating it up again. By the time it bubbles up, your stack trace is totally useless.
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."
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.
It's been best practice for quite some time not to catch { // heh heh he. }.
Nothing about catch requires the program to continue executing as though no exception ever happened, many catches can be fatal but handle emergency cleanup.
If an application crashes on Windows due to an exception, it can be picked up by Microsoft's Watson error logging (now called Windows Error Reporting, I believe). If the user has marked the checkbox "help Microsoft improve Windows by sending crash information" then the dump of the application will be sent to a central location, where it can be triaged and accessed by the application's developer.
Now instead of just a generic entry in a log file, you have a full memory dump of the exception.
Yes, I did include a "this never happens" comment. That is my favorite comment, but only if it is true.
Don't leave empty catch blocks. At least put in some form of logging of the exception, just in case.
The author is right that your code needs to properly react to exceptions and not swallo them. . A global exception handler lets you report to all exceptions, but in order to give proper feedback to the user you definitely have to catch exceptions elsewhere in the code.
Of course, you should be judicious in your usage of try/catch, since it's obviously something that can be abused very poorly.
try { setTimeout(foo, 1000) } catch (ex) { ... }
won't be caught here if foo throws. In some DOM APIs there are 'onerror' handlers (like XHR), in NodeJS the convention is to have an "error" first parameter in the callback (which is null if there's no error).
Also try-catch generates additional scope object inside the catch clause hence it's a bit more expensive than just doing a function call.
Generally try-catch makes sense in JavaScript only locally when executing some external synchronous code that is known to throw exceptions.
Reminds me of when I was trying to write a Win8/Metro app for fun. Turns out in the particular network class I was using 404's throw exceptions. What a horrific design - 404 isn't an unexpected state at all, particularly when calling restful apis. But there we were, a pointless try/catch or nothing.
A lot of the brokenness with exceptions is software that models expected operational state as exceptions.
I've had... I think it was Windows::UI::Input::PointerPoint::GetCurrentPoint throw exceptions if the finger passed in was no longer touching the screen. Sounds fine at first, right? Except...
1) This occurred before "finger released" events, so you'd run into a crash because they thought throwing an exception was better than returning the last known finger position, which would've rightly left me with no error report.
2) This occurred in a nasty rare corner case, making figuring out the reproduction a PITA. I don't think I'm alone in not expecting such a simple function to throw when given a known-to-me-valid fingerId. Worse, the exception was completely undocumented on MSDN -- either explicitly or as a hint from function signature (at least Win32 had the common decency to return BOOL or HRESULT.)
3) I found no method for validating a finger ID, so one had to simply catch the exception and accept the massive framerate dip of exception handling overhead if the user pawed at the screen. Before you mistake that for hyperbolic performance concerns: I could make a smooth 30fps tank to bellow 10fps consistently. I measured!
Touch input isn't the only unexpected thing throwing exceptions for WinRT. The end result of this "throw exceptions whenever you can" mentality is I've been forced to build a habit of wrapping every WinRT API call in extremely wide try/catch blocks to log whatever random undocumented exceptions come crawling out of it. By becoming the rule, it took the "exception" out of "exceptions". I'm sure you'll agree: This is horrifically ugly, slow, and in generally poor taste.
But it's necessary. The other alternative is you hopefully find as many as 90% of the weird junk that crashes your program with exceptions, most of which you don't actually care about in the slightest -- and the other 10% avoid discovery and instead explode your stuff in production, most of which will be for no good reason.
Exceptions, as the name itself indicates, should only be reactions to EXCEPTIONAL situations. Showstoppers.
The adage is: don't use exceptions for flow control. In the case you described, it seems to me that they did just that, and I don't condone that. It's clearly a case of bad, or at least unfortunate API design...
By "whenever you can" I meant "whenever you can once the ground criteria are met", I kind of thought it goes without saying but I should've been more precise
http://www.php.net/manual/en/exception.construct.php