Monthly Archives: November 2011

PHP – Exceptions in PHP5

PHP5 supports Exception model, like C++/C# and Java.

syntax to catch exception:


try {
 //code which can launch an exception
 // [...]
 // manual exception throw
 throw new Exception(“thrown exception”);
 //not executed ! (throw command is caught below
 print “not printed!”;
 }
 catch(Exception $e) { print $e->getMessage();}

this code prints : “thrown exception”.

<!--more-->
 It’s possibile to throw an exception inside a catch construct. The new exception will be caught in the external try-catch block.

try {
 try{
 throw new Exception(“internal exception”);
 }
 catch (Exception $e) { throw new Exception($e->getMessage()); }
 print “not printed!”;
 }
 catch(Exception $e) { print $e->getMessage(); }

This code prints: “internal exception”

Structure of “Exception” built-in class and inheritance


class Exception
 {
 protected $message = ‘Unknown exception’; // exception message
 protected $code = 0; // user defined exception code
 protected $file; // source filename of exception
 protected $line; // source line of exception

function __construct($message = null, $code = 0);

final function getMessage(); // message of exception
 final function getCode(); // code of exception
 final function getFile(); // source filename
 final function getLine(); // source line
 final function getTrace(); // an array of the backtrace()
 final function getTraceAsString(); // formatted string of trace

/* Overrideable */
 function __toString(); // formatted string for display
 }

In case of extension, remember to call the superclass constructor in the extended class constructor
parent::__construct()

Multiple catch constructs
It’s allowed to specify more than one catch after a try construct.
If the exception doesnt’ match with the argument, it will be caught to the next catch block.
Note: an Exception object match also with the objects of its subclasses. Mind the order !


class MyException extends Exception {/* …*/ }

try{
 throw new MyException(“”);
 }
 catch (MyException $e) {// print “MyException”;
 }
 catch (Exception $e) { // never executed
 print “Exception”;
 }

And …

try{
 throw new MyException(“”);
 }
 catch (Exception2 $e) { print “Exception”; }
 catch (Exception $e) { // print “Exception”;
 }
 catch (MyException $e) { print “MyException”; }