0Pricing
PHP Academy · Lesson

Error and Exception Handling

Handle runtime errors and exceptions effectively.

Error and Exception Handling is a free PHP Academy lesson on CoddyKit — lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the PHP Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

1

Error and Exception Handling

Welcome to the lesson on error and exception handling! In this lesson, you’ll learn how to handle errors gracefully and use exceptions to create more reliable and maintainable PHP applications. Let’s get started!

Error and Exception Handling — illustration 1

2

What Are Errors and Exceptions?

Errors: Unexpected issues in your code that prevent it from functioning correctly. Examples include syntax errors and undefined variables.

Exceptions: Special objects that represent errors or unexpected conditions in a program. They can be caught and handled without crashing the application.

Key Difference: Errors are usually fatal, while exceptions can be caught and managed.

3

Types of Errors in PHP

PHP has several types of errors:

  • Parse Errors: Syntax issues that prevent code from being executed.
  • Fatal Errors: Code that PHP cannot execute, such as calling an undefined function.
  • Warning Errors: Issues that do not stop script execution but indicate problems.
  • Notice Errors: Minor issues like accessing an undefined variable.

Key Point: Understanding error types helps in debugging and resolving issues efficiently.

4

Basic Error Handling

Use PHP’s error_reporting() function to control which errors are displayed. Example:

Tip: Use ini_set() to configure error display settings dynamically.

<?php
  // Display all errors
  error_reporting(E_ALL);

  // Hide warnings
  error_reporting(E_ALL & ~E_WARNING);

  echo $undefinedVar; // This will trigger a Notice
?>

5

Custom Error Handling

Create a custom error handler function using set_error_handler(). Example:

Key Point: Custom error handlers are useful for logging and custom error messages.

<?php
  function customErrorHandler($errno, $errstr, $errfile, $errline) {
    echo "Error [$errno]: $errstr in $errfile on line $errline<br>";
  }

  set_error_handler("customErrorHandler");

  echo $undefinedVar; // Triggers custom error handler
?>

6

Using Exceptions

Exceptions provide a structured way to handle errors in PHP. Example:

Key Point: Use the try-catch block to handle exceptions gracefully.

<?php
  try {
    if (!file_exists("example.txt")) {
      throw new Exception("File not found.");
    }
  } catch (Exception $e) {
    echo "Caught exception: " . $e->getMessage();
  }
?>

7

Throwing Exceptions

Use the throw keyword to generate exceptions. Example:

Tip: Throw exceptions for invalid arguments, missing files, or failed database connections.

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

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

8

Logging Errors

Log errors to a file using error_log(). Example:

Key Point: Logging errors helps track issues in production environments without displaying them to users.

<?php
  error_log("An error occurred.", 3, "errors.log");

  echo "Error logged to file.";
?>

9

10

Great Job!

Congratulations! You’ve learned the fundamentals of error and exception handling in PHP, including managing errors, creating custom handlers, and using exceptions for robust error management. In the next lesson, we’ll explore working with regular expressions in PHP. Let’s keep coding!

Error and Exception Handling — illustration 10

Frequently asked questions

Is the “Error and Exception Handling” lesson free?

Yes — the full text of “Error and Exception Handling” is free to read here on the web, and the PHP Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the PHP Academy course, upgrade to CoddyKit PRO.

What will I learn in “Error and Exception Handling”?

Handle runtime errors and exceptions effectively. You practise PHP Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start PHP Academy?

No prior experience is required. PHP Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Error and Exception Handling” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this PHP Academy lesson?

Yes. Every PHP Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Handling Sessions and Cookies
  2. Working with Files
  3. Error and Exception Handling
  4. Using Regular Expressions
← Back to PHP Academy