Exceptions

An Exception object is thrown when an error occurs. It can be caught in a try block, and handled in a catch block. More than one catch blocks may be used to catch various exception classes, and the first matching clause will be used. We can throw our own exceptions.

RESETRUNFULL
<!DOCTYPE html>
<html>
<head></head>
<body><?php
function inverse($x) {
    if (!$x) {
        throw new Exception('Division by zero.');
    }
    else return 1/$x;
}
try {
    echo inverse(4);
    echo inverse(0);  // exception thrown
    echo "This part is not executed.";
} catch (Exception $e) {
    echo '<br />*** Caught exception ***';
    echo "<br /> Message:". $e->getMessage();
    echo "<br /> Code:". $e->getCode();
    echo "<br /> File:". $e->getFile();
    echo "<br /> Line:". $e->getLine();
    echo "<br /> Previous:". $e->getPrevious();
    echo "<br /> Trace String:". $e->getTraceAsString();
}
echo '<br />This part is printed.';
?> </body>
</html>
The thrown object must be an instance of the Exception class or a subclass of Exception. The Exception class has the following members:

<?php
class Exception{
protected $message = 'Unknown exception'; 
private $string;
protected $code = 0;
protected $file;
protected $line;
private $trace;
private $previous; // previous exception if nested exception

public function __construct
     ($message = null, $code = 0, Exception $previous = null);
final private function __clone(); // no cloning of exceptions
final public function getMessage();
final public function getCode();
final public function getFile();
final public function getLine(); 
final public function getTrace(); // an array of the backtrace()
final public function getPrevious(); // previous exception
final public function getTraceAsString(); // formatted trace
public function __toString(); // formatted string for display
}
?>
Exceptions can be nested. An uncaught inner exception will be thrown to the outer try{…} catch(…) {…} block.

RESETRUNFULL
<!DOCTYPE html>
<html>
<head></head>
<body><?php
class E extends Exception{}
class F extends Exception{}
class G extends Exception{}
try{
   try {
      throw new E;
   } catch (F $exc){
      echo "Caught in the inner try block F.";
   } catch (G $exc){
      echo "Caught in the inner try block G.";
   }
} catch (E $exc){
   echo "Caught in the outer try block E.";
}
?> </body>
</html>
An uncaught exception causes a fatal error. Use set_exception_handler($f($e)) to handle any uncaught exceptions. set_exception_handler() takes in the exception $e, and returns the name of the previously defined exception handler. NULL is returned on error or if no exception handler was previously defined. If NULL is passed, resetting the handler to its default state, TRUE is returned.

RESETRUNFULL
<!DOCTYPE html>
<html>
<head></head>
<body><?php
function Exc_Handler($E){
   echo $E->getMessage();
}
set_exception_handler('Exc_Handler');
throw new Exception('Testing the exception handler...');
?> </body>
</html>