What are common built-in exception classes in PHP (SPL exceptions)? PHP में आम built-in exception classes कौन से हैं (SPL exceptions)?
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.
| Class | Use case |
|---|---|
| InvalidArgumentException | A function received an argument of the wrong type or value |
| OutOfRangeException | An illegal index was requested, e.g. array index out of bounds |
| LengthException | A length value is invalid, e.g. an empty required string |
| RuntimeException | An error that can only be detected at runtime, e.g. a failed API call |
| LogicException | An error in program logic that should be fixed by the developer, e.g. calling a method in the wrong state |
| PDOException | Database 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 |
| LengthException | length वैल्यू invalid है, जैसे खाली required string |
| RuntimeException | ऐसी एरर जो सिर्फ runtime पर पता चलती है, जैसे failed API call |
| LogicException | program logic में एरर जो developer को fix करनी चाहिए, जैसे गलत state में method call |
| PDOException | PDO इस्तेमाल करते वक्त 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?