简体   繁体   中英

What is the PHP equivalent to Python's Try: … Except:

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?

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.

try {

    // do stuff ...

} catch (Exception $e) {

    print($e->getMessage());

}

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

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 (ie, 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();
}

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.

PHP 5 has the exception model :

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

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";
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM