Exceptions question

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
evilmonkey
Forum Regular
Posts: 823
Joined: Sun Oct 06, 2002 1:24 pm
Location: Toronto, Canada

Exceptions question

Post 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!
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Post 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.
User avatar
evilmonkey
Forum Regular
Posts: 823
Joined: Sun Oct 06, 2002 1:24 pm
Location: Toronto, Canada

Post 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.
Post Reply