Catching all exceptions and errors

Code that catches all exceptions and errors

try {
    $fv = calc_future_value(10000, 0.06, 9);
} catch (Exception $e) {
    echo 'Error: ' . $e->getMessage();
} catch (Error $e) {
    echo 'Error: ' . $e->getMessage();
}

The message for the error above

Error: Call to undefined function calc_future_value()

A more concise way to catch all errors and exceptions

try {
    $fv = calculate_future_value(10000, 0.06, 9);
} catch (Throwable $e) {
    echo 'Error: ' . $e->getMessage();    
}

Code that catches a ParseError

try {
    require 'calculations.php';
} catch (ParseError $e) {
    echo 'Required file not included: ' . $e->getMessage();
}

The message for the error above

Required file not included: syntax error, unexpected '}', expecting ';'

Code that catches a TypeError

try {
    $average = avg_of_3(5.1, 2.7, 8.2);
} catch (TypeError $e) {
    echo 'Error: ' . $e->getMessage();    
}

The message for the error above

Error: Argument 1 passed to avg_of_3() must be of the type integer, float given

Back