DEV Community

Cover image for How to Handle Exceptions in PHP
Haseeb Mirza
Haseeb Mirza

Posted on

How to Handle Exceptions in PHP

When working with PHP applications, errors are bound to happen. They might be caused by invalid user input, missing files, database connection failures, or unexpected behavior in your code. Instead of letting these errors break your application, PHP provides a powerful mechanism to handle exceptions gracefully.

What is an Exception in PHP?

An exception is an object that represents an error or unexpected event during the execution of a program. When something goes wrong, PHP can "throw" an exception, and you can "catch" it to decide how your application should respond.
This way, instead of showing a blank page or cryptic error message, you can handle the problem more effectively.

Flow of Exception Handling in PHP Applications

In a well-structured PHP application, exceptions flow from the domain layer to the controller layer. As shown in the diagram, the Domain Service executes the core logic. If something goes wrong, it throws a Domain Exception. The Controller, which calls the service, catches this exception and decides how to respond (for example, showing a friendly error message or logging the error). This separation keeps the code clean, makes debugging easier, and ensures that business rules are not mixed with presentation logic.

Types of PHP Exceptions

In PHP Exception Handling, errors can be broadly classified into different types based on their purpose. The most common ones include:
Built-in Exceptions – These are predefined by PHP, such as Exception, ErrorException, InvalidArgumentException, OutOfRangeException, and many others.
Runtime Exceptions – These occur during script execution, such as division by zero, database connection failures, or file handling errors.
Custom Exceptions – User-defined exceptions created by extending the Exception class to handle application-specific problems.
By understanding these types, developers can implement more structured PHP Exception Handling and decide whether to use built-in exceptions or define custom ones.


Basic Exception Handling
The most common way to handle exceptions in PHP is by using try, catch, and optionally finally blocks.

<?php
try {
    // Code that may throw an exception
    $number = 0;
    if ($number == 0) {
        throw new Exception("Division by zero not allowed.");
    }
    echo 10 / $number;
} catch (Exception $e) {
    // Handle the exception
    echo "Error: " . $e->getMessage();
} finally {
    // This block is always executed
    echo " | Execution finished.";
}
?>
Enter fullscreen mode Exit fullscreen mode

Explanation:
• try → The code that may cause an exception.
• catch → Executes if an exception is thrown. You can access details using $e->getMessage(), $e->getCode(), or $e->getFile().
• finally → Runs regardless of whether an exception occurred (useful for cleanup, like closing database connections).

Multiple Catch Blocks
You can catch different types of exceptions separately:

<?php
try {
    throw new InvalidArgumentException("Invalid input provided");
} catch (InvalidArgumentException $e) {
    echo "Caught Invalid Argument: " . $e->getMessage();
} catch (Exception $e) {
    echo "Caught General Exception: " . $e->getMessage();
}   
?>
Enter fullscreen mode Exit fullscreen mode

This way, specific exceptions can be handled differently from general ones.

Creating Custom Exceptions
In large applications, you may want to create your own exception classes to better organize error handling.

<?php
class CustomException extends Exception {}

try {
    throw new CustomException("This is a custom error.");
} catch (CustomException $e) {
    echo "Custom Exception: " . $e->getMessage();
} catch (Exception $e) {
    echo "General Exception: " . $e->getMessage();
}
?>

Enter fullscreen mode Exit fullscreen mode

Custom exceptions make debugging easier and provide more context about what went wrong.

Best Practices for Exception Handling

  1. Don’t ignore exceptions – Always handle them properly instead of suppressing errors.
  2. Use meaningful messages – Clear error messages make debugging much easier.
  3. Log exceptions – Store error details in a log file for developers.
  4. error_log($e->getMessage(), 3, "errors.log");
  5. Avoid exposing sensitive data – Never display database passwords, server details, or stack traces to end users.
  6. Use exceptions for exceptional cases only – Don’t overuse them for simple flow control.

Conclusion

Exception handling in PHP is an essential skill for writing robust and secure applications. By using try, catch, and finally, along with custom exceptions, you can handle errors gracefully and keep your applications running smoothly.
Instead of letting your code crash, learn to catch exceptions, log them, and respond intelligently—your users (and future self) will thank you!

Top comments (0)