minte9
LearnRemember



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
}
Exception class can be extended, to use different nested try/catch blocks.
     code
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
}
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!'



  Last update: 234 days ago