PHP Exceptions Introduction 🎯

beginner
19 min

PHP Exceptions Introduction 🎯

Welcome to our comprehensive guide on PHP Exceptions! In this lesson, we'll explore what exceptions are, why they are essential, and how to use them effectively in your PHP projects. Let's dive in!

Understanding Exceptions πŸ“

Exceptions are runtime errors that occur during the execution of a program. Instead of terminating the entire script, exceptions provide a way to handle errors gracefully and ensure your application continues to run smoothly.

In PHP, you can create custom exceptions or use built-in ones to handle various scenarios.

php
// Custom Exception class CustomException extends Exception { //... } // Built-in Exception try { // Code that may throw an exception } catch (Exception $e) { // Handle the exception }

Types of Exceptions in PHP πŸ“

PHP has three exception types:

  1. Logical Exception: Represents a programming error or logical error.
php
throw new LogicalException("Division by zero error");
  1. Runtime Exception: Represents an error that occurs during runtime, such as trying to access an array key that does not exist.
php
throw new RuntimeException("Array key not found");
  1. Error Exception: Represents a system-level error that occurs during script execution, such as running out of memory.
php
throw new ErrorException("Out of memory error");

Creating Your First Exception πŸ’‘

Let's create a custom exception to handle a situation where a user tries to access a non-existent page.

php
// Custom exception class PageNotFoundException extends Exception { public function __construct($message = 'Page not found') { parent::__construct($message); } } // Example usage try { if (!file_exists('non_existent_page.html')) { throw new PageNotFoundException(); } } catch (PageNotFoundException $e) { echo $e->getMessage(); }

Exception Chaining πŸ’‘

Sometimes, an exception can trigger another exception. In such cases, you can chain exceptions to provide more context.

php
try { // Code that may throw an exception } catch (Exception $e1) { // Another exception triggered by the first one throw new Exception("Exception chained: " . $e1->getMessage(), 0, $e1); }

Exception Propagation πŸ’‘

You can also propagate exceptions to the calling function to let them handle the error.

php
function loadPage($page) { if (!file_exists($page)) { throw new PageNotFoundException(); } //... } try { loadPage('non_existent_page.html'); } catch (PageNotFoundException $e) { echo $e->getMessage(); }

Quiz πŸ’‘

Quick Quiz
Question 1 of 1

Which of the following code snippets represents a custom exception in PHP?

Hope you found this PHP Exceptions Introduction helpful! In the next lesson, we'll dive deeper into exception handling best practices and advanced techniques. Keep coding! πŸ’»πŸ“š