NYCPHP Meetup

NYPHP.org

[nycphp-talk] If/else vs Try/catch

csnyder chsnyder at gmail.com
Wed Nov 28 11:38:18 EST 2007


On Nov 28, 2007 11:25 AM, Ben Sgro (ProjectSkyLine)
<ben at projectskyline.com> wrote:
> Thanks. I'll read up on it now...and post my thoughts.

Trying to explain the benefits of try/catch is like trying to explain
the benefits of OO code: you don't need it to get the job done, but it
really helps if you want to get the job done elegantly.

If you find yourself writing code like:

$success = $obj->process1();
if ( $success ) {
  $success = $obj->process2();
  if ( $success ) {
    $success = $obj->process3();
  }
}
if ( !$success ) {
  exit( "An error ocurred in either process 1, 2, or 3." );
}

... then try/catch is the way out of your nightmare.

try {
  $obj->process1();
  $obj->process2();
  $obj->process3();
} catch Exception( e ) {
  exit( "An error occurred: ".$e->message() );
}

Error handling doesn't need to be part of your program logic anymore.

-- 
Chris Snyder
http://chxo.com/



More information about the talk mailing list