Accept your Exception

Exceptions, yes these are always there in life. However, here I am going to talk about Java exceptions. I know you would be thinking what the basic concept I am picking and what new will I write, but wait I am not going to tell you how to write try...catch.
Yes everyone who knows exception, knows try...catch and there should not be any need to explain it (still I don't now why people ask them in interview). Anyways, Exceptions we all know can be caught using catch, but should we catch them???
In my opinion, I would suggest you not to ever catch any exception. Simplest reason is you can't do anything for an exception that is why it is called exception, something that you have not thought of. You can say but if we don't catch them they will propagate to top layer, yes let them. That is the best thing you can do.
Reasons: Simply saying if an api is saying it can throw an exception, that means it does not know what to do with that. But can you really do something when what you wanted an api to do but it could not do and what you wanted should have, hasn't happened??? We write code so that it should perform what we write but if it did not do that then its of no use, what better could you do in your catch block.
You may say, I can log it, well if you will not catch it there in your code, anyways this is going to go in some log. But if you decide and make a habit of catching them then definitely you can do simple mistakes like eating them, of eating the stack trace and the biggest one is not rolling back the transaction.
Would you really like it to not be able to find the root cause of failure in production just because you ate it, no I don't think so and thus you should not do it.
I have seen too many line of code in my life and I don't remember anyone did any good with exceptions. I have even argued with people who return -1 or null in case of exception and then expect callee to understand that. They even don't think that -1 can be a valid return value.
Also it is good to read your code if you don't have try catch.

Comments