📡 You're offline — showing cached content
New version available!
Quick Access
Tutorials PHP for Beginners Exceptions

Exceptions

6 min read Quiz at the end
Exceptions handle errors cleanly using try, catch, and finally blocks. When something goes wrong, throw an exception and catch it to show a message or log the error. The finally block always runs for cleanup.

Exceptions

// Basic try/catch
try {
    $result = 10 / 0;
    if (!$result) throw new Exception("Division error");
} catch (Exception $e) {
    echo $e->getMessage();  // "Division error"
    echo $e->getCode();
    echo $e->getFile();
    echo $e->getLine();
} finally {
    echo "Always runs";
}

// Multiple catch blocks
try {
    // risky code
} catch (InvalidArgumentException $e) {
    // handle invalid args
} catch (RuntimeException $e) {
    // handle runtime errors
} catch (Exception $e) {
    // catch all
}

// Custom exception
class ValidationException extends RuntimeException {
    public function __construct(string $field, string $msg) {
        parent::__construct("$field: $msg", 422);
    }
}

throw new ValidationException("email", "Invalid format");
Topic Quiz · 5 questions

Test your understanding before moving on

1. Which keyword throws an exception?
💡 throw new Exception("message") throws an exception in PHP.
2. Which block catches exceptions?
💡 try { } catch (Exception $e) { } is the PHP exception handling syntax.
3. What does the finally block do?
💡 finally runs regardless of whether an exception was thrown.
4. What class do custom exceptions extend?
💡 Custom exceptions extend Exception or one of its subclasses.
5. Which method gets the exception message?
💡 getMessage() returns the exception message string.