Friday, May 1, 2009

are you surrounding your code with try-catch block?

I was having a dillema while writing code for a mobile software in J2ME; how would I do the exception handling. I was asked to guard my code with try-catch block. So the first question came to my mind - "is it really necessary to put try-catch in every method or so?". I know some developer never bother about putting any try-catch unless they are bound to do that and some developer blindly put try-catch in every piece of method they write (and they have no idea what they will do with the cought exception). I was having a mindset that I will not put try-catch in my code unless it is absolutely necessary. So, I googled for sometime and found some valuable points:-
  • Try to avoid the usage of exception to determine the programm flow. Throwing exception is a bad way of coding and it should not be used unless you are bound to do that. Raising an exception can be 100000 times slow compared to using a simple return code in a method. Instantiate an exception can be very expensive. An exception generates and stores a snapshot of the stack, what is very time consuming. If you do not have any alternative but to use "throws", its better to reuse the exception instance and you may want to change value of the exception and then throw it.
  • Try-catch block has a overhead. A linked-list like structure has to be maintained by the VM everytime the control-flow enters or exits from a try-catch block even if no exception is thrown from the flow.
  • Never use try-catch block in a loop and try to avoid try-catch block for a complex/hot code in your programm.
  • I would say all depends on requirement of the software you are coding for. If you want your programm would run even after an exception is raised then you may want to use try-catch in your code. If that is not the case then there is no point in using unnecessary try-catch block in your code.