Subjects

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

What are common built-in exception classes in PHP (SPL exceptions)? PHP में आम built-in exception classes कौन से हैं (SPL exceptions)?

Answer

PHP's Standard Library (SPL) provides a hierarchy of exception classes for common scenarios, so you don't need to write a custom exception for every case.

ClassUse case
InvalidArgumentExceptionA function received an argument of the wrong type or value
OutOfRangeExceptionAn illegal index was requested, e.g. array index out of bounds
LengthExceptionA length value is invalid, e.g. an empty required string
RuntimeExceptionAn error that can only be detected at runtime, e.g. a failed API call
LogicExceptionAn error in program logic that should be fixed by the developer, e.g. calling a method in the wrong state
PDOExceptionDatabase errors when using PDO
function setAge(int $age): void {
    if ($age < 0) {
        throw new InvalidArgumentException('Age cannot be negative');
    }
}

Interview tip: Using SPL exceptions instead of a generic Exception makes catch blocks more precise and self-documenting - reach for a custom exception only when SPL doesn't fit.

PHP की Standard Library (SPL) आम scenarios के लिए exception classes का एक hierarchy देती है, ताकि हर केस के लिए custom exception न लिखनी पड़े।

Classउपयोग
InvalidArgumentExceptionफंक्शन को गलत type या वैल्यू का argument मिला
OutOfRangeExceptionअवैध index request हुआ, जैसे array index out of bounds
LengthExceptionlength वैल्यू invalid है, जैसे खाली required string
RuntimeExceptionऐसी एरर जो सिर्फ runtime पर पता चलती है, जैसे failed API call
LogicExceptionprogram logic में एरर जो developer को fix करनी चाहिए, जैसे गलत state में method call
PDOExceptionPDO इस्तेमाल करते वक्त database errors
function setAge(int $age): void {
    if ($age < 0) {
        throw new InvalidArgumentException('Age cannot be negative');
    }
}

इंटरव्यू टिप: generic Exception की बजाय SPL exceptions इस्तेमाल करने से catch blocks ज़्यादा precise और self-documenting बनते हैं - custom exception सिर्फ तब बनाएं जब SPL fit न बैठे।

Was this answer clear?