PHP Exceptions
⚠️ PHP Exceptions Tutorial
In PHP, exceptions are used to handle runtime errors in a structured way. Exceptions allow you to catch and handle errors gracefully instead of letting the script crash.
1️⃣ Basic Try-Catch
Output:
✅ throw is used to generate an exception.
✅ catch is used to handle the exception.
2️⃣ Multiple Catch Blocks (PHP 7+)
You can catch different exception types separately:
-
Specific exceptions should come before general
Exception.
3️⃣ Using finally Block
The finally block executes regardless of whether an exception occurred:
Output:
4️⃣ Creating Custom Exceptions
You can create your own exception class:
✅ Useful for application-specific errors.
5️⃣ Exception Methods
| Method | Description |
|---|---|
$e->getMessage() |
Returns error message |
$e->getCode() |
Returns exception code |
$e->getFile() |
Returns file where exception occurred |
$e->getLine() |
Returns line number |
$e->getTrace() |
Returns stack trace as array |
$e->getTraceAsString() |
Returns stack trace as string |
Example:
6️⃣ Key Points
-
Exceptions are object-oriented error handling.
-
Use
tryfor risky code,catchto handle exceptions. -
finallyexecutes always, even if no exception occurred. -
Create custom exception classes for application-specific errors.
-
Exception methods provide detailed debugging information.
