0PricingLogin
PHP Academy · Lesson

Try, Catch, and Finally

Handle runtime exceptions gracefully with try/catch/finally blocks.

Exceptions vs Errors

PHP has two ways to signal problems:

  • Errors — traditional PHP notices/warnings/fatals (discussed previous lesson)
  • Exceptions — objects thrown when something exceptional happens; caught with try/catch

Exceptions are the modern, preferred approach for handling recoverable errors.

Throwing an Exception

Use throw to signal that something went wrong:

<?php
function divide(float $a, float $b): float {
    if ($b == 0) {
        throw new InvalidArgumentException('Cannot divide by zero');
    }
    return $a / $b;
}

echo divide(10, 2);   // 5
// divide(10, 0);     // throws exception

All lessons in this course

  1. PHP Error Types and Reporting
  2. Try, Catch, and Finally
  3. Creating Custom Exceptions
  4. Logging Errors and Best Practices
← Back to PHP Academy