What is the best way to catch an exception(Industry standrad practice )in large application programs ?
1. Is it better to catch the exception in the method(Where thrown) itself ? or 2. In the main method (catching all exception right here itself ?)
"You cannot change the truth but truth can change you "
Joined: Oct 13, 2005
Difficult to give a simple answer. If you ask n expert Java programmers about exceptions you will get n+1 different opinions!
I think the answer to your question is: neither nor. You can't give a hard-and-fast rule because a rule which works well for 75% of occasions will give really bad results in the other 25%, but this is what I suggest:
Not in the main method; by the time an Exception has propagated that far you have lost contact with your application. Also your main method will become too large with all the exception handling.
Not in the method where it is thrown, otherwise the calling method will not "know" that there is any problem. In fact you are liable to get null returns, or files not written to, which the rest of the application is not "aware of," which can give rise to other problems later.
Here the most likely place for an Exception is in the writeToFile() method. If you catch the Exception there, then save() will "think" all has gone well. What you need is some sort of code in save() which will take appropriate action if the data are not saved in the file. So that is where you can catch the Exception, and take whatever action is most appropriate.
That's what I think, for a lot of Exceptions, but maybe the best answer to your question is,
"Wherever you can best handle the Exception."
Anybody else . . . ?
Joined: Oct 30, 2001
I certainly do agree that there is no single best place to handle all exceptions, and that the best short answer is to handle it wherever you can handle it best.
Many beginners make the mistake of trying to handle all exceptions close to where they can be thrown. This often results in very poor handling (the worst of which is just ignoring the exception), because there is nothing sensible that can be done at that point.
I don't agree with the point above that the main() method is the wrong place to handle exceptions. In some types of program, particularly small single-threaded utilities, there is nothing to be done about certain types of exception, other than inform the user and exit the program; that is best done in main().
Betty Rubble? Well, I would go with Betty... but I'd be thinking of Wilma.<br /> <br />#:^P
Joined: Jan 04, 2008
For help on this topic, I recommend this article, Exception-Handling Antipatterns by Tim McCune. It has some great explanations of what to do and what not to do.