Subjects

All subjects Django Java Python React Spring Boot JavaScript PHP
Sign Up Free
Question 3 of 10 · Error & Exception Handling
Interview question

How do you create and use custom exception classes in PHP? PHP में custom exception classes कैसे बनाएं और इस्तेमाल करें?

Answer

Create a class that extends Exception (or a more specific built-in subclass) to represent domain-specific error conditions with extra context.

class InsufficientFundsException extends Exception {
    public function __construct(
        private float $requested,
        private float $available
    ) {
        parent::__construct(
            "Requested {$requested} but only {$available} available"
        );
    }

    public function getShortfall(): float {
        return $this->requested - $this->available;
    }
}

function withdraw(float $amount, float $balance): void {
    if ($amount > $balance) {
        throw new InsufficientFundsException($amount, $balance);
    }
}

try {
    withdraw(500, 200);
} catch (InsufficientFundsException $e) {
    echo $e->getMessage();
    echo 'Shortfall: ' . $e->getShortfall();
}

Interview tip: Point out that custom exceptions let you catch specific business errors separately from generic ones, and can carry structured data (like getShortfall() here) instead of just a string message.

Exception (या किसी विशेष built-in subclass) को extend करके एक class बनाएं जो domain-specific error conditions को extra context के साथ दर्शाए।

class InsufficientFundsException extends Exception {
    public function __construct(
        private float $requested,
        private float $available
    ) {
        parent::__construct(
            "Requested {$requested} but only {$available} available"
        );
    }

    public function getShortfall(): float {
        return $this->requested - $this->available;
    }
}

function withdraw(float $amount, float $balance): void {
    if ($amount > $balance) {
        throw new InsufficientFundsException($amount, $balance);
    }
}

try {
    withdraw(500, 200);
} catch (InsufficientFundsException $e) {
    echo $e->getMessage();
    echo 'Shortfall: ' . $e->getShortfall();
}

इंटरव्यू टिप: बताएं custom exceptions specific business errors को generic errors से अलग catch करने देते हैं, और सिर्फ string message नहीं बल्कि structured data (जैसे यहाँ getShortfall()) भी ले जा सकते हैं।

Was this answer clear?