PROGRAMMING

 
REMEMBERS




Last update:   29-10-2021

Try Catch

An exception from a try block is passed on to catch block.
 
try {
    //$number = 1/0;
    $number = -1;

    if ($number < 0) {
        throw new Exception ("The number is negative");
    }
} catch (Exception $e) {
    echo $e->getMessage(); // Division by zero
}
... 4 lines
 
Exception class can be extended, to use different nested try/catch blocks.
 
class MyException extends Exception {}

try {
    $number = -1;

    if ($number < 0) {
        throw new MyException("Invalid number");
    }

    $number = 1/0;

} catch (Exception $e) {
    echo $e->getMessage(); // Division by zero
} catch (MyException $e) {
    echo $e->getMessage(); // Division by zero
}
... 7 lines
 
PHP allows to define a catch-all function that is automatically called.
 
function handleUncaughtExcetion($e) {
    echo $e->getMessage();
}

set_exception_handler("handleUncaughtExcetion");

throw new Exception ("My error!"); // My error!

echo "This is never displayed";

// Without exception handler, we will have:
// Uncaught exception 'Exception' with message 'My error!'
... 3 lines
 

Questions    
Late static binding

        A B C D E F
🔔
1/2