Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

exception handling once or several times

 
Raj Ohadi
Ranch Hand
Posts: 316
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 24212
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic