PBBG Snippets

Log In or Register

Making PHP throw exceptions instead of errors

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
PHP natively produces fatal errors when something goes wrong.

These can be handled using a custom error handler,
but they don't permit the use of try-catch blocks in your code.
The following is a quick and painless solution.

<?php
function error_handler_exception($errno, $errstr, $errfile, $errline ) {
    throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
}
set_error_handler('error_handler_exception', E_ERROR);
?>

Now you can enclose things in a try-catch block
and handle the error gracefully.

<?php
try {
    do_something();
} catch (Exception $e) {
   print "Something broke, and it broke hard.";
}
?>
Happy error handling!

Comments

You need to be logged in to comment on snippets.