13.09.2016 Views

PHP and MySQL Web Development 4th Ed-tqw-_darksiderg

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

194 Chapter 7 Error <strong>and</strong> Exception H<strong>and</strong>ling<br />

The constructor for this class takes two parameters: a message <strong>and</strong> a code.They are<br />

intended to represent an error message <strong>and</strong> an error code number. Both of these parameters<br />

are optional.<br />

Finally, underneath your try block, you need at least one catch block.A catch block<br />

looks like this:<br />

catch (typehint exception)<br />

{<br />

// h<strong>and</strong>le exception<br />

}<br />

You can have more than one catch block associated with a single try block. Using<br />

more than one would make sense if each catch block is waiting to catch a different type<br />

of exception. For example, if you want to catch exceptions of the Exception class, your<br />

catch block might look like this:<br />

catch (Exception $e)<br />

{<br />

// h<strong>and</strong>le exception<br />

}<br />

The object passed into (<strong>and</strong> caught by) the catch block is the one passed to (<strong>and</strong><br />

thrown by) the throw statement that raised the exception.The exception can be of any<br />

type, but it is good form to use either instances of the Exception class or instances of<br />

your own user-defined exceptions that inherit from the Exception class. (You see how<br />

to define your own exceptions later in the chapter.)<br />

When an exception is raised, <strong>PHP</strong> looks for a matching catch block. If you have<br />

more than one catch block, the objects passed in to each should be of different types so<br />

that <strong>PHP</strong> can work out which catch block to fall through to.<br />

One other point to note is that you can raise further exceptions within a catch block.<br />

To make this discussion a bit clearer, let’s look at an example. A simple exception h<strong>and</strong>ling<br />

example is shown in Listing 7.1.<br />

Listing 7.1<br />

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

Saved successfully!

Ooh no, something went wrong!