Meaningless Drivel is fun!*
The moose likes Beginning Java and the fly likes exception handling once or several times Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "exception handling once or several times" Watch "exception handling once or several times" New topic
Author

exception handling once or several times

Raj Ohadi
Ranch Hand

Joined: Jun 30, 2006
Posts: 316
code snippet --

if(a == -1) {
try {
myCal.doIt_1();
} catch (Excpetion_1 e) {}
catch (Exception_2 e) {}
} else if (a == 0) {
try {
myCal.doIt_2();
} catch (Excpetion_1 e) {}
catch (Exception_2 e) {}
} else if (a == 1) {
try {
myCal.doIt_3();
} catch (Excpetion_1 e) {}
catch (Exception_2 e) {}
}

Can I change it into --

try {
if(a == -1) { myCal.doIt_1(); }
else if (a == 0) {myCal.doIt_2(); }
else if (a == 1) {myCal.doIt_3(); }
} catch (Excpetion_1 e) {}
catch (Exception_2 e) {}
}

Does this change look better ?
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24166
    
  30

I'm assuming that in your real program, those "catch" blocks won't be empty -- you're doing something to handle your errors, right? At least reporting them?

But to answer your question, yes -- this is a very good thing to do. Concentrating the error handling all in one place, and the main program flow in another, definitely makes code easier to read. As a general rule, when this is easy to do, then I recommend you do it.


[Jess in Action][AskingGoodQuestions]
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: exception handling once or several times
 
Similar Threads
Exception
problem with insert and select
A Special TextEdit control for Date
Internet Explorer XMLHTTPRequest problem
Try-catches cannot be found