Daily Shaarli

All links of one day in a single page.

May 5, 2013

Python to PHP: try…except for non-users exceptions (aka "errors" in PHP)

There might be some easier ways to do that but that's the easiest I found so far…

As usual, not surprisingly, Python is better (IMO).

Python:

try:
foo()
except ValueError:
bar()

PHP:

It's actually pretty easy when you implement your own errors (throw new Exception then catch it with a try…catch) but how to catch errors this easily and being able to handle them that easily? Well, turn them into exceptions!

set_error_handler(function($errno, $errstr){throw new Exception($errno);});
try
{
file_get_contents('lol');
}
catch(Exception $e)
{
echo 'Error n°',$e->getMessage();
}
restore_error_handler();

I still prefer Python… I think I'll always do. </PHPTROLL> </PYTHONFAN>