Error handling in PHP – how to detect problems, respond to them, and keep your application running when something goes wrong.
What error handling is
Error handling means anticipating problems in your code and deciding what to do when they happen. That might mean logging the error, showing a message to the user, or handling it quietly in the background.
Basic error handling with die()
The simplest approach is die(), which stops the script and can output a message.
<?php
if(!file_exists("example.txt")) {
die("File not found.");
} else {
$file = fopen("example.txt", "r");
// read file
}
?>
It works, but it is abrupt. Fine for quick scripts; not ideal for production.
Custom error handlers
For more control, define your own handler with set_error_handler().
<?php
function customError($errno, $errstr) {
echo "<b>Error:</b> [$errno] $errstr<br>";
echo "Ending Script";
die();
}
set_error_handler("customError");
echo($test);
?>
You decide what happens when an error occurs – log it, display a friendly message, or stop the script.
Error reporting levels
Use error_reporting() to control which types of errors PHP reports.
<?php
// Report all errors except E_NOTICE
error_reporting(E_ALL & ~E_NOTICE);
// Report simple running errors
error_reporting(E_ERROR | E_WARNING | E_PARSE);
?>
Exceptions
Exceptions handle conditions that need special treatment. Use throw to signal a problem and try-catch to handle it.
Throwing an exception
<?php
function checkNum($number) {
if($number>1) {
throw new Exception("Value must be 1 or below");
}
return true;
}
try {
checkNum(2);
echo 'If you see this, the number is 1 or below';
}
catch(Exception $e) {
echo 'Message: ' .$e->getMessage();
}
?>
The try-catch block
Run risky code in the try block. Handle any exception in the catch block.
<?php
try {
// Code that may throw an exception
}
catch (Exception $e) {
// Code to handle the exception
}
?>
Logging errors
Often it is better to log errors than show them to users. error_log() writes to a file or the server log.
<?php
error_log("Error!", 3, "/var/tmp/my-errors.log");
?>
Best practices
- Use exception handling: catch recoverable errors with try-catch rather than letting the script crash.
- Separate user errors from system errors: show friendly messages for user mistakes; log system errors for debugging.
- Do not expose sensitive information: keep database paths, stack traces, and internal details out of user-facing messages.
- Monitor your error logs: check them regularly so you catch problems before users report them.
There is no single right approach. Match your error handling to what the application actually needs – a contact form and a payment gateway have different requirements.

