← Back to PHP Course | Chapter 13: Error Handling | Lesson 3 of 5

PHP Custom Exceptions

एक custom exception आपका अपना named तरह का problem है, टूटे हुए oven के लिए एक special alarm जैसा। यह ज़्यादा clear बनाता है कि क्या गलत हुआ और आपको इसका exactly response देने देता है।
Syntax
php
class CustomException extends Exception {
    // optional extra methods and properties
}

try {
    throw new CustomException("message");
} catch (CustomException $e) {
    echo $e->getMessage();
}

एक Custom Exception Class बनाना

PHP की built-in Exception class को extend करना आपको अपने खुद के exception types (जैसे InvalidUserException) define करने देता है, जो हर error को same treat करने के बजाय specific failure categories को अलग-अलग catch और handle करना possible बनाता है।

उदाहरण: Creating a Custom Exception Class

php
<?php
class InvalidUserException extends Exception {}

// Try running this block; jump to `catch` if it throws
try {
    // Throw a new `InvalidUserException` with message "User not found"
    throw new InvalidUserException("User not found");
// Catch InvalidUserException $e
} catch (InvalidUserException $e) {
    // Print `$e->getMessage()` to the output
    echo $e->getMessage();
}
?>

Custom Error Formatting

क्योंकि एक custom exception class बस एक class है, आप इसमें अपने खुद के methods और properties add कर सकते हैं -- उदाहरण के लिए एक method जो internal error details से एक user-friendly message format करे।

उदाहरण: Custom Error Formatting

php
<?php
// Define the class `AppException`, inheriting from `Exception`
class AppException extends Exception {
    // Define the function `friendlyMessage` with no parameters
    function friendlyMessage() {
        // Return `"Oops: " . $this->getMessage()` from this function
        return "Oops: " . $this->getMessage();
    }
}
// Try running this block; jump to `catch` if it throws
try {
    // Throw a new `AppException` with message "Database unreachable"
    throw new AppException("Database unreachable");
// Catch AppException $e
} catch (AppException $e) {
    // Print `$e->friendlyMessage()` to the output
    echo $e->friendlyMessage();
}
?>

Custom Exceptions Throw करना

एक generic के बजाय एक custom exception throw करना validation failures को self-documenting code में बदल देता है: एक StockUnavailableException catch करना एक bare Exception से कहीं ज़्यादा intent communicate करता है।

उदाहरण: Throwing Custom Exceptions

php
<?php
class StockUnavailableException extends Exception {}

// Define the function `order` taking `$qty`, `$stock`
function order($qty, $stock) {
    // Check whether `$qty > $stock`
    if ($qty > $stock) {
        // Throw a new `StockUnavailableException` with message "Not enough stock"
        throw new StockUnavailableException("Not enough stock");
    }
}
// Try running this block; jump to `catch` if it throws
try {
    // Call `order(5, 2)`
    order(5, 2);
// Catch StockUnavailableException $e
} catch (StockUnavailableException $e) {
    // Print `$e->getMessage()` to the output
    echo $e->getMessage();
}
?>

कई Custom Catches

कई custom exception types को अलग-अलग catch करना हर एक को अपना recovery path trigger करने देता है -- एक network call retry करना user को invalid input fix करने के लिए कहने से पूरी तरह अलग है।

उदाहरण: Multiple Custom Catches

php
<?php
class NetworkException extends Exception {}
class ValidationException extends Exception {}

// Define the function `process` taking `$type`
function process($type) {
    if ($type === "network") throw new NetworkException("Connection lost");
    // Throw a new `ValidationException` with message "Bad input"
    throw new ValidationException("Bad input");
}
// Try running this block; jump to `catch` if it throws
try {
    // Call `process("network")`
    process("network");
// Catch NetworkException $e
} catch (NetworkException $e) {
    // Print `"Retrying: " . $e->getMessage()` to the output
    echo "Retrying: " . $e->getMessage();
// Catch ValidationException $e
} catch (ValidationException $e) {
    // Print `"Fix input: " . $e->getMessage()` to the output
    echo "Fix input: " . $e->getMessage();
}
?>

Custom Exceptions को Rethrow करना

कभी-कभी आप एक exception को locally log करना चाहते हैं और फिर भी stack में आगे किसी caller को इसे handle करने देना चाहते हैं; एक catch block के अंदर throw $e से इसे re-throw करना exactly यही करता है original error खोए बिना।

उदाहरण: Rethrowing Custom Exceptions

php
<?php
class AppException extends Exception {}

// Define the function `risky` with no parameters
function risky() {
    // Throw a new `AppException` with message "Something broke"
    throw new AppException("Something broke");
}
// Try running this block; jump to `catch` if it throws
try {
    // Try running this block; jump to `catch` if it throws
    try {
        // Call `risky()`
        risky();
    // Catch AppException $e
    } catch (AppException $e) {
        // Call `error_log($e->getMessage())`
        error_log($e->getMessage());
        throw $e;
    }
// Catch AppException $e
} catch (AppException $e) {
    // Print `"Handled higher up: " . $e->getMessage()` to the output
    echo "Handled higher up: " . $e->getMessage();
}
?>
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. Exception (या किसी दूसरी Throwable class) को extend न करना, ताकि custom class throw न हो सके।
  2. constructor override करना और parent::__construct() call करना भूल जाना, ताकि message और code खो जाएँ।
  3. custom class से पहले base Exception catch करना, ताकि custom handler कभी न चले।
🔒

Chapter Quiz — Complete all 5 topics to unlock

0/5 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.