🎓 A1Learner
🔍
0 of 38 lessons completed

Turning Warnings into Exceptions

An error handler is a function that PHP calls when a warning or a notice is raised. set_error_handler can make that handler throw an exception instead, so try and catch can deal with the warning.

A warning prints and the program carries on

A warning reports a problem without stopping the program. This program reads a variable that was never set, and the line after the read still prints.

<?php
$value = $missing;
echo "Program continued\n";

The handler turns the warning into an exception

The handler is a closure, a function written inside the call with no name of its own. It throws an ErrorException that carries the warning message, and the catch block prints it.

<?php
set_error_handler(function ($severity, $message) {
  throw new ErrorException($message);
});
try {
  $value = $missing;
  echo "Not reached\n";
} catch (ErrorException $e) {
  echo "caught: ", $e->getMessage(), "\n";
}

restore_error_handler brings the warning back

The first read is converted and caught, like the one before it. After restore_error_handler runs, the second read prints its warning line in the old way.

<?php
set_error_handler(function ($severity, $message) {
  throw new ErrorException($message);
});
try {
  $value = $missing;
} catch (ErrorException $e) {
  echo "caught: ", $e->getMessage(), "\n";
}
restore_error_handler();
$other = $alsoMissing;
echo "Program continued\n";

Example

<?php
set_error_handler(function ($severity, $message) {
  throw new ErrorException($message);
});
$settings = ["name" => "Book Nook"];
try {
  echo $settings["theme"], "\n";
} catch (ErrorException $e) {
  echo "caught: ", $e->getMessage(), "\n";
}
echo $settings["name"], "\n";

Key points

  • A warning is a message PHP prints when something is wrong but the program can carry on.
  • set_error_handler registers a function as the handler for warnings and notices.
  • A handler that throws an ErrorException turns a warning into an exception.
  • The message of that exception is the warning text, without the file path part.
  • restore_error_handler removes the registered handler and brings the earlier one back.

In this example, a settings array holds a name but no theme. The handler turns the missing key warning into an ErrorException, and the catch block prints its message. The last line reads the name key, which exists, and prints Book Nook.

Note

Reading a variable that was never set raises a warning, not an exception, until a handler converts it.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does restore_error_handler do?