1

I cannot make try work. I tried this:

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

Which results on the error:

Warning: Division by zero in /var/www/vhosts/saliganando.com/webs/momemi/apis/interpret-bot.php on line 6 

I tried modifying error_reporting() and ini_set() but I have only managed to either remove the warning or display it, but 'Caught exception...' is never shown.

What am I doing wrong?

lisovaccaro
  • 32,502
  • 98
  • 258
  • 410

1 Answers1

4

That code will never generate an exception. It generates a warning. You would need to capture the warning within an error handler (with set_error_handler()) to process that error.

See the docs on exceptions for plenty of examples on how Exceptions work and how to catch them, including one to mimic the functionality you're looking for:

function inverse($x) {
    if (!$x) {
        throw new Exception('Division by zero.');
    }
    else return 1/$x;
}

try {
    echo inverse(5) . "\n";
    echo inverse(0) . "\n";
} catch (Exception $e) {
    echo 'Caught exception: ',  $e->getMessage(), "\n";
}

Which generates:

0.2
Caught exception: Division by zero.
nickb
  • 59,313
  • 13
  • 108
  • 143
  • Do not forget you could throw your own exception in function registred with set_error_handler. – sectus Feb 23 '13 at 03:37