Exception Handling

লেসন ৮ / ৩৯

Exception কী?

Exception হলো runtime-এ ঘটা একটি অস্বাভাবিক পরিস্থিতি বা ভুল। OOP-তে এটি একটি object যা throw করা হয় ও catch করা যায়।

try-catch ব্লক

function divide($a, $b) {
    if ($b == 0) {
        throw new Exception("শূন্য দিয়ে ভাগ করা যায় না");
    }
    return $a / $b;
}

try {
    echo divide(10, 2);   // 5
    echo divide(10, 0);    // Exception ছুঁড়বে
    echo divide(20, 4);    // এই লাইন চলবে না
} catch (Exception $e) {
    echo "ভুল: " . $e->getMessage();
}
echo "প্রোগ্রাম চলছে";    // ✅ চলবে

Exception-এর Methods

try {
    throw new Exception("কিছু ভুল হয়েছে", 500);
} catch (Exception $e) {
    echo $e->getMessage();   // কিছু ভুল হয়েছে
    echo $e->getCode();       // 500
    echo $e->getFile();       // কোন ফাইলে
    echo $e->getLine();       // কোন লাইনে
    echo $e->getTrace();      // full trace
    echo $e->getTraceAsString();
}

finally ব্লক

Exception হোক বা না হোক — finally ব্লক সবসময় চলবে।

try {
    $file = fopen("data.txt", "r");
    // কিছু কাজ
    throw new Exception("সমস্যা!");
} catch (Exception $e) {
    echo "ভুল ধরা পড়েছে\n";
} finally {
    echo "Cleanup...\n";
    if (isset($file)) fclose($file);
}

একাধিক Exception Type

try {
    // কোড
} catch (TypeError $e) {
    echo "Type ভুল: " . $e->getMessage();
} catch (ValueError $e) {
    echo "Value ভুল: " . $e->getMessage();
} catch (Exception $e) {
    echo "অন্য কোনো ভুল: " . $e->getMessage();
}

// PHP 8+ এ একাধিক catch একসাথে
try {
    // ...
} catch (TypeError | ValueError $e) {
    echo "Type/Value ভুল: " . $e->getMessage();
}

Custom Exception Class

class DatabaseException extends Exception {}
class ValidationException extends Exception {
    private $field;

    public function __construct($message, $field) {
        parent::__construct($message);
        $this->field = $field;
    }

    public function getField() {
        return $this->field;
    }
}

// ব্যবহার
function createUser($data) {
    if (empty($data["email"])) {
        throw new ValidationException("ইমেইল আবশ্যক", "email");
    }
    if (!filter_var($data["email"], FILTER_VALIDATE_EMAIL)) {
        throw new ValidationException("ইমেইল সঠিক নয়", "email");
    }
    // ... DB save
}

try {
    createUser(["email" => "invalid"]);
} catch (ValidationException $e) {
    echo "Field [{$e->getField()}]: {$e->getMessage()}";
}

Built-in Exception Classes

  • Exception — সব exception-এর base
  • Error — PHP Engine level errors
  • TypeError — ভুল টাইপ
  • ValueError — ভুল মান
  • ArgumentCountError — ভুল argument সংখ্যা
  • DivisionByZeroError
  • PDOException — database

Best Practice

// ✅ Specific exception
throw new ValidationException("ইমেইল সঠিক নয়", "email");

// ❌ Generic message
throw new Exception("ভুল");

// ✅ Multiple validation
$errors = [];
if (empty($name)) $errors[] = "নাম দিন";
if (empty($email)) $errors[] = "ইমেইল দিন";
if ($errors) throw new ValidationException(implode(", ", $errors));