Originally Posted by
Junky
However, with variables it is recommended that you declare them in the smallest possible scope. You should do the same with try/catch statements. By that I mean if you have 20,000 lines of code and only one of them can throw an exception then put the try around that one line not the whole lot.
Having said that, methods should be kept as short as possible (i.e. not 20,000 lines!), and a big advantage of exceptions is that they allow messy error handling to be removed from the body of the code, so in practice, you might want the try/catch to surround the
block of code that might throw the exception, rather than the single line (I'm assuming the try/catch isn't being positioned just to indicate an exception-throwing call!). Of course, there are trivial exceptions (ha!) to the guideline, like using Thread.sleep(), where, in the absence of an interrupting thread, it's common to put the try..catch in the body of the code, because it's typically very small & self-contained, with a one-line try block and an empty or one liner catch. But I have seen even this put into a separate sleep() method (particularly when the sleep time is parameterized).