Errors and exceptions are inevitable in any programming language, but handling them properly is crucial for creating robust and user-friendly applications. In this lesson, we'll explore error and exception handling in PHP, including the use of try-catch blocks and custom exception classes.

Error Handling

By default, PHP displays errors and warnings on the web page, which can be helpful during development but may expose sensitive information in a production environment. You can control how PHP handles errors using the error_reporting() function and ini_set() function.

// Disable all error reporting
error_reporting(0);

// Enable all error reporting
error_reporting(E_ALL);

// Display errors on the web page
ini_set("display_errors", 1);

// Log errors to a file
ini_set("log_errors", 1);
ini_set("error_log", "/path/to/error.log");

Exception Handling

Exceptions are used to signal exceptional conditions that require special handling. You can use the try-catch block to handle exceptions.

try {
  // Code that may throw an exception
  if ($denominator == 0) {
    throw new Exception("Division by zero is not allowed.");
  }
  $result = $numerator / $denominator;
} catch (Exception $e) {
  // Handle the exception
  echo "Error: " . $e->getMessage();
}

Custom Exception Classes

You can create custom exception classes by extending the base Exception class. This allows you to define more specific exception types and add additional properties or methods.

class DivisionByZeroException extends Exception {
  public function __construct($message = "Division by zero is not allowed.", $code = 0, Exception $previous = null) {
    parent::__construct($message, $code, $previous);
  }
}

try {
  if ($denominator == 0) {
    throw new DivisionByZeroException();
  }
  $result = $numerator / $denominator;
} catch (DivisionByZeroException $e) {
  echo "Error: " . $e->getMessage();
}

Finally Block

The optional finally block allows you to execute code regardless of whether an exception was thrown or not. This can be useful for cleanup tasks, such as closing database connections or file handles.

try {
  // Code that may throw an exception
} catch (Exception $e) {
  // Handle the exception
} finally {
  // Code to be executed regardless of whether an exception was thrown or not
}

Actionable Work:

Practice error and exception handling in PHP by completing the following exercises:

  1. Create a PHP script that reads a CSV file and inserts the data into a database. Use exception handling to catch and handle any errors that may occur, such as file not found or database connection errors.
  2. Create a custom exception class for handling database errors, which includes additional information about the database connection and query. Modify the previous exercise to use this custom exception class.
  3. Implement a simple calculator application in PHP that takes user input for two numbers and an operation (addition, subtraction, multiplication, or division). Use error and exception handling to validate the input and handle any errors, such as division by zero.