Page 1 of 1

Exceptions question

Posted: Sun Dec 17, 2006 10:14 pm
by evilmonkey
Hello,

This is such a n00b question, I feel ashamed asking given my post count here at devnetwork. Nevertheless, I got into OOP now (joined the dark side, so to speak :P ), and there's one thing I cannot understand, and that's exceptions. I will use an example of a user ID getting passed through $_GET and checking against the database for whether or not that user exists. How is the throw...try...catch different from doing something like this:

Code: Select all

$userid = $_GET['userid'];
if (is_valid($userid)){ //where is_valid is a custom method that returns true if the user exists and false if he doesn't
   $user = new User ($userid); 
}
else{
     echo "mistake in userid";
}
Can someone please walk me through doing the same thing in throw...try...catch and tell me how it is superior?

Thank you and happy holidays!

Posted: Mon Dec 18, 2006 12:46 am
by Chris Corbyn
You can simplify logic with try/catch:

Code: Select all

try {
    //run a load of statements, many of which may throw an exception
} catch (SomethingException $e) {
    echo "Oops, something went wrong: " . $e->getMessage();
} catch (AnotherthingException $e) {
    echo "Ooop, another thing went wrong: " . $e->getMessage();
}
You don't need to keep running checks if it's safe to continue with your logic in the try block since once an exception is throw, all execution is halted in that block and you go straight to catch.

They also help prevent "transparent" failures to end-users even if not checked for since PHP will treat it like a fatal error if not caught.

Posted: Mon Dec 18, 2006 7:19 am
by evilmonkey
Hmm, interesting. Do you have a good tutorial on this? I looked in the PHP manual, but that assumes that the reader is already familiar with the construct.