尝试除了PHP

How could I perform the equivalent to an open try:this except:pass in Python?

I have the following code:

$banana = true;
unserialize($banana);

And it returns the error:

Warning: array_keys() expects parameter 1 to be array, boolean given

Which is expected, as I fed it a boolean.

This is just an example; I am using unserialize(), but I'm not purposely feeding it booleans. I need it to work this way.

Since unserialize doesn't throw an exception, there is nothing to catch. One of the workarounds is using the silence operator (@) and check whether the outcome of the unserialize method equals false.

$foo = @unserialize($bar);
if ($foo === false && $bar !== 'b:0;') {
    // Unserialize went wrong
}
set_error_handler(function ($errno, $errstr) {
    throw new Exception($errstr, 0);
}, E_NOTICE);

try {
    $result = unserialize($banana); // correct
} catch (Exception $e) {
    $result = array();  // default value
}
restore_error_handler();


print_r($result);