0

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Jamus
  • 865
  • 4
  • 11
  • 28
  • 2
    Have you looked at [exception handling?](http://www.php.net/manual/en/language.exceptions.php) – Lix Feb 12 '14 at 09:26
  • 1
    If you're looking specifically for a solution with `unserialize`: possible duplicate of [Check if string is serialised in PHP](http://stackoverflow.com/questions/2878218/check-if-string-is-serialized-in-php); if you're generally looking for `try..catch`, this does not apply here since those aren't exceptions. – deceze Feb 12 '14 at 09:27
  • By default you cannot catch notices, warnings and errors (and a few others). You can only catch `Exception`s. Also, the warning in this question has nothing to do with your code. You never use `array_keys()` in the code. – Sverri M. Olsen Feb 12 '14 at 09:30

2 Answers2

2

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
}
Kevin Op den Kamp
  • 565
  • 1
  • 8
  • 22
2
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);