25.09.2014 Views

ZEND PHP 5 Certification STUDY GUIDE

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

130 ” Object Oriented Programming in <strong>PHP</strong><br />

Throwing Exceptions<br />

Exceptions are usually created and thrown when an error occurs by using the throw<br />

construct:<br />

i<br />

Although it is common practice to do so, you don’t need to create the Exception object<br />

directly in the throw expression.<br />

if ($error) {<br />

throw new Exception ("This is my error");<br />

}<br />

Exceptions then “bubble up” until they are either handled by the script or cause a<br />

fatal exception. The handling of exceptions is performed using a try...catch block:<br />

try {<br />

if ($error) {<br />

throw new Exception ("This is my error");<br />

}<br />

} catch (Exception $e) {<br />

// Handle exception<br />

}<br />

In the example above, any exception that is thrown inside the try{} block is going to<br />

be caught and passed on the code inside the catch{} block, where it can be handled<br />

as you see fit.<br />

Note how the catch() portion of the statement requires us to hint the type of Exception<br />

that we want to catch; one of the best features of exceptions is the fact that<br />

you can decide which kind of exception to trap. Since you are free to extend the base<br />

Exception class, this means that different nested try..catch blocks can be used to<br />

trap and deal with different types of errors:<br />

Licensed to 482634 - Amber Barrow (itsadmin@deakin.edu.au)<br />

class myException extends Exception { }<br />

try {<br />

try {

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!