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.
Basic Try-Catch
Output:
throwis used to generate an exception.catchis used to handle the exception.
Multiple Catch Blocks (PHP 7+)
You can catch different exception types separately:
Specific exceptions should come before general
Exception.
Using finally Block
The finally block executes regardless of whether an exception occurred:
Output:
Creating Custom Exceptions
You can create your own exception class:
Useful for application-specific errors.
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:
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.
