Exceptional handling and try catch in php with syntax and examples
Exception handling is a mechanism to handle runtime errors in a controlled manner. PHP provides try-catch blocks to handle exceptions.
Syntax:
try {
// code that may throw an exception
} catch (ExceptionType $e) {
// code to handle the exception
}
Example:
try {
$x = 10 / 0;
} catch (DivisionByZeroError $e) {
echo "Error: " . $e->getMessage();
}
Try-Catch Blocks:
- try: Contains code that may throw an exception
- catch: Catches and handles the exception
- finally: Optional block that executes regardless of an exception
Example:
try {
$x = 10 / 0;
} catch (DivisionByZeroError $e) {
echo "Error: " . $e->getMessage();
} finally {
echo "Finally block executed";
}
Exception Types:
- Exception: Base exception class
- TypeError: Type-related exceptions
- DivisionByZeroError: Division by zero exceptions
- PDOException: PDO-related exceptions
Throwing Exceptions:
- throw: Throws an exception
Example:
function divide($a, $b) {
if ($b == 0) {
throw new DivisionByZeroError("Cannot divide by zero");
}
return $a / $b;
}
try {
echo divide(10, 0);
} catch (DivisionByZeroError $e) {
echo "Error: " . $e->getMessage();
}
Custom Exceptions:
- Create custom exception classes extending the Exception class
Example:
class CustomException extends Exception {
public function __construct($message) {
parent::__construct($message);
}
}
try {
throw new CustomException("Custom error message");
} catch (CustomException $e) {
echo "Error: " . $e->getMessage();
}
Best Practices:
1. Use try-catch blocks for error handling
2. Catch specific exception types
3. Use finally blocks for cleanup code
4. Throw exceptions for errors
5. Create custom exceptions for application-specific errors
6. Test exception handling thoroughly
By understanding exception handling and try-catch in PHP, you can write robust and error-free code that handles runtime errors gracefully.