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

PHP try-catch

try-catch एक trapeze के नीचे एक safety net जैसा है: आप कुछ risky try करते हैं, और अगर यह fail हो, catch हिस्सा problem पकड़ लेता है ताकि show चलता रहे।
Syntax
php
try {
    // code that might fail
    throw new Exception("message");
} catch (Exception $e) {
    echo $e->getMessage();
} finally {
    // always runs
}

try-catch का Introduction

एक try-catch block आपको try section के अंदर risky operations -- जैसे एक database call जो fail हो सकती है -- contain करने देता है, जबकि catch section define करता है कि अगर actually कुछ गलत हो तो क्या होता है, पूरी script crash होने के बजाय।

उदाहरण: Introduction to try-catch

php
<?php
// Try running this block; jump to `catch` if it throws
try {
    // Declare `$result`, set to `10 / 0`
    $result = 10 / 0;
// Catch DivisionByZeroError $e
} catch (DivisionByZeroError $e) {
    // Print `"Caught: " . $e->getMessage()` to the output
    echo "Caught: " . $e->getMessage();
}
?>

Exception Object

हर caught Exception object useful diagnostic details carry करता है -- इसका message, एक optional error code, और वह file और line जहाँ यह throw हुआ -- जिन्हें आप inspect करके decide कर सकते हैं कि कैसे respond करना है या क्या log करना है।

उदाहरण: The Exception Object

php
<?php
// Try running this block; jump to `catch` if it throws
try {
    // Throw a new `Exception` with message `"Something failed", 42`
    throw new Exception("Something failed", 42);
// Catch Exception $e
} catch (Exception $e) {
    // Print `$e->getMessage() . " (code: " . $e->getCode() . ")"` to the output
    echo $e->getMessage() . " (code: " . $e->getCode() . ")";
}
?>

Exceptions Throw करना

throw keyword वह तरीका है जिससे आपका अपना code किसी problem का signal देता है, तुरंत normal execution को halt करके नज़दीकी matching catch block में jump करते हुए, एक runtime error जैसे ही।

उदाहरण: Throwing Exceptions

php
<?php
// Define the function `checkAge` taking `$age`
function checkAge($age) {
    // Check whether `$age < 0`
    if ($age < 0) {
        // Throw a new `Exception` with message "Age cannot be negative"
        throw new Exception("Age cannot be negative");
    }
    // Return `$age` from this function
    return $age;
}
// Try running this block; jump to `catch` if it throws
try {
    // Call `checkAge(-5)`
    checkAge(-5);
// Catch Exception $e
} catch (Exception $e) {
    // Print `$e->getMessage()` to the output
    echo $e->getMessage();
}
?>

कई catch Blocks

जब आप कई distinct तरह की failures की उम्मीद करें, कई catch blocks को stack करना आपको हर एक को अलग तरह से handle करने देता है -- बस उन्हें सबसे specific exception type से सबसे general की ओर order करें, क्योंकि PHP उन्हें top से bottom check करता है।

उदाहरण: Multiple catch Blocks

php
<?php
// Try running this block; jump to `catch` if it throws
try {
    // Throw a new `InvalidArgumentException` with message "Bad input"
    throw new InvalidArgumentException("Bad input");
// Catch InvalidArgumentException $e
} catch (InvalidArgumentException $e) {
    // Print `"Specific: " . $e->getMessage()` to the output
    echo "Specific: " . $e->getMessage();
// Catch Exception $e
} catch (Exception $e) {
    // Print `"General: " . $e->getMessage()` to the output
    echo "General: " . $e->getMessage();
}
?>

finally Block

एक finally block के अंदर का code हमेशा चलता है, चाहे try succeed हुआ हो या एक exception catch हुआ हो, जो इसे किसी file handle या database connection बंद करने जैसे cleanup के लिए natural जगह बनाता है।

उदाहरण: The finally Block

php
<?php
// Try running this block; jump to `catch` if it throws
try {
    // Print "Trying...\n" to the output
    echo "Trying...\n";
    // Throw a new `Exception` with message "Failed"
    throw new Exception("Failed");
// Catch Exception $e
} catch (Exception $e) {
    // Print "Caught: " . $e->getMessage() . "\n" to the output
    echo "Caught: " . $e->getMessage() . "\n";
// Runs no matter what, whether or not an exception was thrown
} finally {
    // Print "Cleanup always runs" to the output
    echo "Cleanup always runs";
}
?>
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 catch करना और catch block को खाली छोड़ देना, जो error को पूरी तरह छुपा देता है।
  2. specific catch blocks से पहले एक general catch (Exception $e) रखना, ताकि specific वाले कभी न चलें।
  3. यह उम्मीद करना कि try/catch ordinary warnings और notices catch कर लेगा, जो exceptions नहीं हैं जब तक आप उन्हें convert न करें।
🔒

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.