try/catch handles thrown Throwables, while finally executes cleanup around success or failure.
What It Does
try/catch handles thrown Throwables, while finally executes cleanup around success or failure. The following examples distinguish a normal use case, a boundary case and a practical application.
Requirements and Compatibility
PHP 8.x and a local test environment. Apply input validation, correct error handling and the requirements of any optional libraries.
The code focuses on the core concept. Production implementation may also need routes, validation, persistence, authorization or deployment tooling.
Example 1: Basic Behavior
Start with the smallest meaningful working case.
<?php
try { throw new RuntimeException('Service unavailable'); } catch (RuntimeException $e) { echo 'Retry later'; } finally { echo ' | cleanup'; }
Example 2: Another Case
Examine the edge case and the observable result.
<?php
function parseCount(string $raw): int { $n = filter_var($raw, FILTER_VALIDATE_INT); if ($n === false) throw new InvalidArgumentException('Bad count'); return $n; }
try { parseCount('abc'); } catch (InvalidArgumentException $e) { echo 'Invalid input'; }
Practical Example: Putting It to Use
finally runs resource cleanup on both success and exception paths.
<?php
$resource = fopen('php://temp', 'w+');
try { fwrite($resource, 'ready'); rewind($resource); echo stream_get_contents($resource); } finally { fclose($resource); }
Important Behavior and Edge Cases
Catch only failures you can meaningfully handle; do not swallow exceptions silently.
Comparison with Related Functions or Approaches
| Option | What it means in practice |
|---|---|
| try, catch, and finally | try/catch handles thrown Throwables, while finally executes cleanup around success or failure. |
| Related approach | finally releases resources even when a catch block returns or rethrows. |
Common Beginner Mistakes
| Mistake | Correct approach |
|---|---|
| Ignoring the important boundary for try, catch, and finally | Catch only failures you can meaningfully handle; do not swallow exceptions silently. |
| Assuming a related mechanism has the same behavior | finally releases resources even when a catch block returns or rethrows. |
Key Takeaways
- try/catch handles thrown Throwables, while finally executes cleanup around success or failure.
- Catch only failures you can meaningfully handle; do not swallow exceptions silently.
- finally releases resources even when a catch block returns or rethrows.
Before adapting these examples, verify the return values, test the failure paths and confirm that your application meets its security and environment requirements.