PHP Exceptions

try, catch, finally and custom exceptions.

✍️ 2 exercises in this lesson

Throw an exception when something goes wrong and catch it where you can handle it.

  • throw new Exception("message");
  • try { } catch (Exception $e) { } finally { }
  • Catch several types: catch (TypeError | ValueError $e)
  • Create your own: class PaymentException extends Exception {}

Key Takeaways: PHP Exceptions

Mastering PHP Exceptions helps you write clean and reliable PHP code. Follow standard conventions, test edge cases, and keep logic simple. Try running the code example below and complete the exercises to build confidence.

PHP Exceptions Code Example

PHP
<?php
class InsufficientFundsException extends Exception {}

function withdraw(float $balance, float $amount): float {
    if ($amount > $balance) {
        throw new InsufficientFundsException("Balance too low for Rs $amount");
    }
    return $balance - $amount;
}

try {
    echo withdraw(5000, 2000) . "<br>";
    echo withdraw(5000, 9000) . "<br>";
} catch (InsufficientFundsException $e) {
    echo "Error: " . $e->getMessage() . "<br>";
} finally {
    echo "Done.";
}
Output
3000
Error: Balance too low for Rs 9000
Done.
Run this example on your own computer. The "Get Started" lesson shows how to set it up.

PHP Exceptions Practice Exercises

Check what you learned in “PHP Exceptions”.

/ 2 solved
Fill in the blank

Throw an exception.

 new Exception("Something went wrong");
✓ Correct! Not quite. Try again.
Multiple choice

Which block always runs after try/catch?

✓ Correct! Not quite. Try again.
to save your exercise progress.
Finished this lesson?
Mark it complete to track your progress.

Stuck on something?

Ask the community in the CodesInTech forum.

Need a developer?

Learning on your own is great — and when you need professional help, our team builds custom software, websites and mobile apps for clients worldwide.

Explore Our Services