YouTip LogoYouTip

Php Error Handling

# PHP Error and Exception Handling In PHP 7 and later, the way errors are reported has changed significantly. Unlike the traditional error reporting mechanism of PHP 5, most errors are now thrown as **`Error`** exceptions. This modern approach allows developers to handle runtime errors gracefully using standard exception-handling structures, preventing fatal crashes and improving application stability. --- ## The Throwable Hierarchy In PHP, both `Error` and `Exception` implement the `Throwable` interface. Because `Error` does not extend from the `Exception` class, you cannot catch an `Error` using a standard `catch (Exception $e)` block. To catch both errors and exceptions, you must catch them individually, catch the base `Error` class, or catch the `Throwable` interface. ### PHP Exception and Error Hierarchy * **`Throwable`** (Interface) * **`Error`** * `ArithmeticError` * `DivisionByZeroError` * `AssertionError` * `CompileError` * `ParseError` * `TypeError` * `ArgumentCountError` * `ValueError` (Introduced in PHP 8.0) * `UnhandledMatchError` (Introduced in PHP 8.0) * **`Exception`** * `ErrorException` * `RuntimeException` * ... (Other user-defined and built-in exceptions) --- ## Handling Errors and Exceptions ### 1. Using Try/Catch Blocks You can catch specific errors or general `Error` instances just like standard exceptions. If an error is thrown and there is no matching `try/catch` block, PHP will look for an exception handler registered via `set_exception_handler()`. If none is registered, the error will fall back to a traditional Fatal Error. ### 2. Catching All Throwables To write a catch-all block that handles both standard exceptions and engine errors, type-hint against `Throwable`: ```php try { // Code that may throw an Exception or an Error } catch (Throwable $t) { // Executed for both Exceptions and Errors echo "Caught: " . $t->getMessage(); } ``` --- ## Code Examples ### Example 1: Catching a DivisionByZeroError The following example demonstrates how a division-by-zero operation throws a `DivisionByZeroError` which is caught and handled gracefully. ```php n % 0; return (string)$value; } catch (DivisionByZeroError $e) { // Handle the error gracefully return "Error occurred: " . $e->getMessage(); } } } $mathOperationsObj = new MathOperations(); echo $mathOperationsObj->doOperation(); ?> ``` #### Output: ```text Error occurred: Modulo by zero ``` --- ### Example 2: Catching a TypeError PHP throws a `TypeError` when a function argument or return value does not match its declared type. ```php getMessage(); } ?> ``` #### Output: ```text Type Error Caught: Argument 2 passed to addNumbers() must be of the type int, string given ``` --- ## Key Considerations * **Strict Types:** To fully leverage `TypeError` exceptions for type mismatches, ensure you declare strict types (`declare(strict_types=1);`) at the top of your PHP files. * **The `Throwable` Interface:** You cannot implement the `Throwable` interface directly in user-defined classes. Instead, extend the `Exception` class to create custom exceptions. * **Backward Compatibility:** Legacy PHP 5 code that relies on custom error handlers (`set_error_handler()`) may not catch engine errors thrown as `Error` exceptions. You should register a global exception handler using `set_exception_handler()` to catch unhandled `Throwable` instances. * **Resource Cleanup:** Use the `finally` block to execute cleanup code (like closing database connections or file handles) regardless of whether an error or exception was thrown.
← C Nested IfPhp Use Statement β†’