Web Analytics

PHP Error Handling & Exceptions

Advanced~25 min read

Proper error handling makes your applications robust and maintainable. Exceptions provide a clean way to handle errors without cluttering your code!

Output
Click Run to execute your code

Try-Catch Block

<?php
try {
    $file = fopen('nonexistent.txt', 'r');
    if (!$file) {
        throw new Exception("File not found");
    }
} catch (Exception $e) {
    echo "Error: " . $e->getMessage();
}
?>

Custom Exceptions

<?php
class DatabaseException extends Exception {}

try {
    throw new DatabaseException("Connection failed");
} catch (DatabaseException $e) {
    echo "DB Error: " . $e->getMessage();
}
?>

Finally Block

<?php
try {
    // Code that might fail
} catch (Exception $e) {
    // Handle error
} finally {
    // Always runs (cleanup)
}
?>

Summary

  • try-catch: Handle exceptions
  • throw: Raise exception
  • finally: Always executes
  • Custom exceptions: Extend Exception class

What's Next?

Next, learn about Regular Expressions - powerful pattern matching!