Handling Errors and Exceptions in PHP: The Complete Guide ๐Ÿš€

Handling Errors and Exceptions in PHP: The Complete Guide ๐Ÿš€

Imagine you're building a website, and suddenlyโ€”BOOM! ๐Ÿ’ฅ Your page breaks with a cryptic error message. Ever been there? ๐Ÿ˜… Thatโ€™s why error handling is crucial in PHP!

A well-handled error can:
โœ… Prevent your site from crashing
โœ… Improve user experience
โœ… Help debug problems easily

In this step-by-step guide, youโ€™ll learn how to catch errors and exceptions like a pro, with real-world examples and a mini-project at the end! ๐Ÿš€


๐ŸŽฏ Understanding PHP Errors

PHP has four main types of errors:

Error Type Description Example
Fatal Error Stops script execution completely Calling an undefined function
Parse Error Syntax mistake in the code Missing ; in PHP
Warning Non-fatal, script continues Using a missing file
Notice Minor issue, script continues Using an undefined variable

๐Ÿ”ฅ How to see errors?
Enable error reporting with:

error_reporting(E_ALL);
ini_set('display_errors', 1);

This displays all PHP errors while developing.


1๏ธโƒฃ Handling Errors with try...catch

Basic Error Handling

<?php
try {
    echo 10 / 0; // Division by zero (error!)
} catch (Exception $e) {
    echo "Error: " . $e->getMessage();
}
?>

๐Ÿš€ What happens?

  • try runs the code that might fail.
  • catch handles the error gracefully.
  • The script wonโ€™t crash unexpectedly.

2๏ธโƒฃ Using set_error_handler() for Custom Error Messages

Custom Error Handler

<?php
function customError($errno, $errstr) {
    echo "Error [$errno]: $errstr <br>";
}
set_error_handler("customError");

// Trigger an error
echo 10 / 0;
?>

๐Ÿ”ฅ Why use this?

  • set_error_handler() lets you define how errors are handled globally.
  • Prevents ugly PHP error messages.

3๏ธโƒฃ Using error_log() to Store Errors

Logging Errors to a File

<?php
function logError($errno, $errstr) {
    error_log("Error [$errno]: $errstr", 3, "errors.log");
}
set_error_handler("logError");

// Simulate an error
echo 10 / 0;
?>

๐Ÿ”ฅ Why use this?

  • Stores errors in errors.log instead of showing them to users.
  • Useful for debugging in production.

4๏ธโƒฃ Handling Exceptions in PHP

Exceptions are better than errors for handling unexpected issues.

Using throw to Trigger an Exception

<?php
function divide($a, $b) {
    if ($b == 0) {
        throw new Exception("Cannot divide by zero!");
    }
    return $a / $b;
}

try {
    echo divide(10, 0);
} catch (Exception $e) {
    echo "Caught Exception: " . $e->getMessage();
}
?>

๐Ÿš€ What happens?

  • throw new Exception() manually triggers an exception.
  • The catch block prevents crashes.

5๏ธโƒฃ Using finally to Clean Up

Example: Closing a Database Connection

<?php
try {
    $conn = new PDO("mysql:host=localhost;dbname=zeroexp_dev", "root", "");
    echo "Connected successfully!";
} catch (Exception $e) {
    echo "Database Error: " . $e->getMessage();
} finally {
    echo "<br>Cleaning up resources.";
}
?>

๐Ÿ”ฅ Why use finally?

  • Runs whether or not an exception occurs.
  • Great for closing connections, releasing memory, or logging actions.

๐ŸŽฏ Mini Project: User Login with Error Handling

Letโ€™s build a real-world login system that handles:
โœ… Missing username/password
โœ… Database connection errors
โœ… Wrong credentials

login.html

<form action="login.php" method="post">
    Username: <input type="text" name="username"><br>
    Password: <input type="password" name="password"><br>
    <input type="submit" value="Login">
</form>

login.php

<?php
session_start();

try {
    $conn = new PDO("mysql:host=localhost;dbname=zeroexp_dev", "root", "");
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    if ($_SERVER["REQUEST_METHOD"] == "POST") {
        $username = trim($_POST["username"] ?? '');
        $password = trim($_POST["password"] ?? '');

        if (empty($username) || empty($password)) {
            throw new Exception("Both fields are required!");
        }

        // Fake authentication (replace with database check)
        if ($username === "zerodev" && $password === "secret123") {
            $_SESSION["username"] = $username;
            header("Location: dashboard.php");
        } else {
            throw new Exception("Invalid credentials!");
        }
    }
} catch (Exception $e) {
    echo "Error: " . $e->getMessage();
}
?>

dashboard.php

<?php
session_start();
if (!isset($_SESSION["username"])) {
    echo "Access denied! <a href='login.html'>Login here</a>";
    exit;
}

echo "Welcome, " . $_SESSION["username"] . "! <a href='logout.php'>Logout</a>";
?>

logout.php

<?php
session_start();
session_unset();
session_destroy();
header("Location: login.html");
?>

โœ… Whatโ€™s Happening?

  • login.php checks for errors (empty fields, wrong credentials).
  • If login is successful, the user is redirected to dashboard.php.
  • If not, an error message is displayed.
  • logout.php clears the session and logs out the user.

๐Ÿ”ฅ Boom! You now have a secure PHP login system with error handling! ๐Ÿš€


๐Ÿš€ Final Thoughts

Now you know how to handle errors like a pro!
โœ… Use try...catch to prevent crashes
โœ… Use set_error_handler() for custom error handling
โœ… Use error_log() to track issues in production
โœ… Use exceptions for better error control

๐Ÿ‘‰ Next: Introduction to MySQL with PHP

Happy coding! ๐ŸŽ‰๐Ÿš€

Leave a Reply