Memory App
Programming
 




An exception that is thrown in try{} block is passed on to catch{} block.

<?php
    $error = true;
    try {
        if ($error) {
            throw new Exception ("This is my error");
        }
    } catch (Exception $e) {
        echo $e->getMessage();
            // output: This is my error
    }
Exception class can be extended, to use different nested try/catch blocks.
    
<?php
    class myException extends Exception {
    }
    
    try {
        // ...
    } catch (myException $e) {
        echo $e->getMessage();
    }
    } catch (Exception $e) {
        echo $e->getMessage();
    }
PHP allows to define a catch-all function that is automatically called.

<?php
    function handleUncaughtExcetion($e) {
        echo $e->getMessage();
    }

    set_exception_handler("handleUncaughtExcetion");

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

    echo "This is never displayed";

    // Without exception handler, will have:
    // Fatal error: Uncaught exception 'Exception' with message 'My error!'


Questions



Top Reference > Programming
0/0 (80)  
Not Logged