Real applications constantly face unexpected situations — a missing file, invalid user input, or a failed database connection. Without proper handling, these problems crash your script entirely. PHP Error Handling gives you the tools to catch problems gracefully and respond in a controlled way.
This is Tutorial 4 of 10 in our PHP Advanced series. You will learn how try/catch blocks work, how exceptions carry error information, and how to build your own custom exception classes.
What is PHP Error Handling?
PHP Error Handling refers to techniques that let your script detect problems and respond to them safely, instead of stopping abruptly with an unhandled error message visible to users. The core tool for this is the exception system, built around try, catch, and throw.
The try/catch Block
A try block wraps code that might fail. If something goes wrong inside it, PHP immediately jumps to the matching catch block instead of crashing the entire script.
<?php
try {
echo "This code runs normally.";
} catch (Exception $e) {
echo "Something went wrong: " . $e->getMessage();
}
?>
In this simple example, nothing actually fails, so the catch block never runs. Real PHP Error Handling becomes useful once you introduce code that can genuinely throw an error.
Throwing an Exception
You can manually trigger an exception using the throw keyword, along with the new Exception class and a custom message describing what went wrong.
<?php
function divideNumbers($a, $b) {
if ($b == 0) {
throw new Exception("Division by zero is not allowed.");
}
return $a / $b;
}
try {
echo divideNumbers(10, 0);
} catch (Exception $e) {
echo "Error: " . $e->getMessage();
}
?>
Here, PHP Error Handling prevents the script from crashing when dividing by zero. Instead, the catch block captures the thrown exception and displays a friendly message.
The getMessage() Method
Every exception object includes a getMessage() method, which returns the exact text you passed when creating the exception. This makes it easy to display clear feedback about what specifically went wrong.
<?php
try {
throw new Exception("Custom error message here.");
} catch (Exception $e) {
echo $e->getMessage();
}
?>
Using finally
PHP Error Handling also supports a finally block, which always runs after try and catch, regardless of whether an exception occurred or not. This is useful for cleanup tasks like closing a file or database connection.
<?php
try {
echo "Trying something risky.";
throw new Exception("Failed!");
} catch (Exception $e) {
echo "Caught: " . $e->getMessage();
} finally {
echo "This always runs, no matter what.";
}
?>
Catching Multiple Exception Types
Sometimes different problems require different responses. PHP Error Handling allows multiple catch blocks, each targeting a specific exception type, checked in order from top to bottom.
<?php
try {
throw new InvalidArgumentException("Invalid input provided.");
} catch (InvalidArgumentException $e) {
echo "Input error: " . $e->getMessage();
} catch (Exception $e) {
echo "General error: " . $e->getMessage();
}
?>
PHP includes several built-in exception types beyond the base Exception class, such as InvalidArgumentException and RuntimeException, each suited to describing a more specific category of failure.
Creating Custom Exceptions
For more meaningful PHP Error Handling in larger applications, you can create your own exception classes by extending the built-in Exception class. This lets you attach custom logic or additional details to specific error types in your project.
<?php
class InsufficientFundsException extends Exception {
public function customMessage() {
return "Custom Alert: " . $this->getMessage();
}
}
function withdraw($balance, $amount) {
if ($amount > $balance) {
throw new InsufficientFundsException("Not enough balance to withdraw.");
}
return $balance - $amount;
}
try {
echo withdraw(100, 500);
} catch (InsufficientFundsException $e) {
echo $e->customMessage();
}
?>
Custom exceptions make your PHP Error Handling far more descriptive, allowing different parts of a large application to catch and respond to very specific failure scenarios rather than generic ones. For complete official documentation, refer to the official PHP exceptions manual.
Best Practices for Error Handling
Always catch the most specific exception types before the general Exception class, since PHP checks catch blocks in order. Never expose raw technical error messages directly to end users in a production application — log the details internally and show a simple, friendly message instead.
What’s Next?
You now understand PHP Error Handling using try/catch, throw, finally, multiple catch blocks, and custom exception classes. In the next tutorial, we will explore file handling in PHP, including reading, writing, and managing file uploads.
If you missed the previous lesson, check out Tutorial 3: PHP Interfaces Guide, or explore all lessons in our PHP category.
Practice Exercise
Complete the following tasks to reinforce what you learned in this tutorial:
- Create a PHP file named
error-handling-practice.php - Write a function called
checkAge()that throws an exception if the age passed in is negative - Wrap the function call in a try/catch block and display the exception message if triggered
- Add a finally block that always echoes “Age check complete” regardless of the outcome
- Create a custom exception class called
InvalidEmailExceptionextending Exception - Write a function that throws InvalidEmailException if a given string does not contain the “@” symbol
- Catch the custom exception separately from a general Exception catch block
Bonus Challenge: Create a function called processOrder() that throws different exception types depending on the problem — one for an empty cart and another custom exception for insufficient stock — then handle both with separate catch blocks in the correct order.

