• Post Reply Bookmark Topic Watch Topic
  • New Topic

overhead of having a lot of code in a single try block  RSS feed

 
Basavaraju Banakar
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What is the overhead of having a lot of code in a single try block and catch all the exceptions that are thrown in seperate catch blocks??
Would it be better to have seperate try/catch blocks to handle each chunck of code that potentially throws an exception.
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
First of all, "large" blocks should never be very large, because good style dictates that methods should rarely be more than a few dozen lines of code, and should usually be much less than that.
It's generally better style (and technically will be slightly more efficient) to have your try blocks be as large as possible, and put all the exception handlers together at the bottom of a routine.
But you should worry about style, and not about micro-efficiency issues. Write clear, readable, correct code, and if performance turns out to be a problem, you can always go back and optimize it.
 
Jeroen Wenting
Ranch Hand
Posts: 5093
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you MUST have a long codeblock which cannot be broken up into separate functions, IMO it's better to break it into functional units and have a try/catch block for each.
That way it can be easier to determine which line caused the problem more easily as it provides finer granularity.
But most likely you'll be able to split the block into several functions if you can split it into several try/catch blocks which would then be the better choice.
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Jeroen Wenting:
That way it can be easier to determine which line caused the problem more easily as it provides finer granularity.

That would be a valid argument for C++, I suppose, but in Java, you get line numbers for free, so I don't think it matters.
There's a general principle, articulated by many style gurus (Thomas and Hunt, Cargill, Stroustrup) that error-handling code and "normal" code should be kept separate; using one long try block concentrates error handling at the bottom of the routine, so that the flow of the main logic is clearer.
If, of course, the routine can continue after an exception, then yes, you'd want to use small local try blocks. But if the routine will clean up and abort after any exception, which is the common case, then one big try block makes more sense to me.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!