views:

114

answers:

6

I am a strong Python programmer, but not quite there when it comes to PHP. I need to try something, and if that doesn't work out, do something else.


This is what it would look like in Python:

try:
      print "stuf"
except:
      print "something else"

What would this be in PHP?

+7  A: 

http://php.net/manual/en/language.exceptions.php

try {
    print 'stuff';
} catch (Exception $e) {
    var_dump($e);
}

Note: this only works for exceptions, not errors.

See http://www.php.net/manual/en/function.set-error-handler.php for that.

Petah
+1  A: 
try {

    // do stuff ...

} catch (Exception $e) {

    print($e->getMessage());

}

See http://php.net/manual/en/language.exceptions.php

ts
This was what I needed, thanks. I'll accept this answer when I can in about 8 or 9 mins.
Zachary Brown
@Zachary how did it go?
mizipzor
@mizipzor, it worked great! @ts, sorry I hadn't accepted it yet, forgot to last night.
Zachary Brown
A: 

PHP 5 has the exception model:

try {
    print 'stuff';
} catch (Exception $e) {
    echo 'Caught exception: ',  $e->getMessage(), "\n";
}
Russell Dias
A: 

Assuming you're trying to catch exceptions, take a look at http://php.net/manual/en/language.exceptions.php

You could try something like

try {
echo "Stuff";
} catch (Exception $e) {
echo "Something Else";
}
Parker
+1  A: 

PHP does not natively support error catching like Python does, unless you override the default behavior and set your own error handler. PHP's try - catch was only recently added to the language in version 5, and it can only catch exceptions you explicitly throw.

So basically, PHP distinguishes between errors and exceptions. Errors haven't been modularized and made available to the user like they have been in Python. I believe that's related to the fact that PHP began as a collection of dynamic web scripts, grew and gained more features over time, and only more recently offered improved OOP support (i.e., version 5); whereas Python fundamentally supports OOP and other meta-functionality. And exception handling from the beginning.

Here's an example usage (again, a throw is necessary, or else nothing will be caught):

function oops($a)
{
    if (!$a) {
        throw new Exception('empty variable');
    }
    return "oops, $a";
}

try {
    print oops($b);
} catch (Exception $e) {
    print "Error occurred: " . $e->getMessage();
}
willell
+1  A: 

You can handle PHP errors like they were exceptions by using set_error_handler

In this error handler function you can throw various exception, according to error level for instance.

By doing this you can treat any error (including programming errors) in a common way.

Benoit
+1 for a useful point that the other answers missed.
Spudley