PHP Exceptions

Exceptions
Even though they have been a staple of object-oriented programming for years, exceptions have only recently become part of the PHP arsenal. Exceptions provide an error control mechanism that is more fine-grained than traditional PHP fault handling, and that allows for a much greater degree of control.

There are several key differences between “regular” PHP errors and exceptions:
  • Exceptions are objects, created (or “thrown”) when an error occurs
  • Exceptions can be handled at different points in a script’s execution, and different types of exceptions can be handled by separate portions of a script’s code
  • All unhandled exceptions are fatal
  • Exceptions can be thrown from the __construct method on failure
  • Exceptions change the flow of the application


The Basic Exception Class
As we mentioned in the previous paragraph, exceptions are objects that must be direct or indirect (for example through inheritance) instances of the Exception base class. The latter is built into PHP itself, and is declared as follows:

class Exception {
// The error message associated with this exception
protected $message = ’Unknown Exception’;
// The error code associated with this exception
protected $code = 0;
// The pathname of the file where the exception occurred
protected $file;
// The line of the file where the exception occurred
protected $line;
// Constructor
Function __construct ($message = null, $code = 0);
// Returns the message
final function getMessage();
// Returns the error code
final function getCode();
// Returns the file name
final function getFile();
// Returns the file line
final function getLine();
// Returns an execution backtrace as an array
final function getTrace();
// Returns a backtrace as a string
final function getTraceAsString();
// Returns a string representation of the exception
Function __toString();
}

Almost all of the properties of an Exception are automatically filled in for you by the interpreter—generally speaking, you only need to provide a message and a code, and all the remaining information will be taken care of for you.

Since Exception is a normal (if built-in) class, you can extend it and effectively create your own exceptions, thus providing your error handlers with any additional information that your application requires.
Throwing Exceptions
Exceptions are usually created and thrown when an error occurs by using the throw construct:

if ($error) {
throw new Exception ("This is my error");
}

Exceptions then “bubble up” until they are either handled by the script or cause a fatal exception. The handling o f exceptions is performed using a try...catch block:

try {
if ($error) {
throw new Exception ("This is my error");
}
} catch (Exception $e) {
// Handle exception
}

In the example above, any exception that is thrown inside the try{} block is going to be caught and passed on the code inside the catch{} block, where it can be handled as you see fit.

Note how the catch() portion of the statement requires us to hint the type of Exception that we want to catch; one of the best features of exceptions is the fact that you can decide which kind of exception to trap. Since you are free to extend the base Exception class, this means that different nested try..catch blocks can be used to trap and deal with different types of errors:
class myException extends Exception { }
try {
try {
try {
new PDO("mysql:dbname=zce");
throw new myException("An unknown error occurred.");
} catch (PDOException $e) {
echo $e->getMessage();
}
} catch(myException $e) {
echo $e->getMessage();
}
} catch (Exception $e) {
echo $e->getMessage();
}

In this example, we have three nested try... catch blocks; the innermost one will only catch PDOException objects, while the next will catch the custom myException objects and the outermost will catch any other exceptions that we might have missed.

Rather than nesting the try...catch blocks like we did above, you can also chain just the catch blocks:

try {
new PDO("mysql:dbname=zce");
throw new myException("An unknown error occurred.");
} catch (PDOException $e) {
echo $e->getMessage();
} catch (myException $e) {
echo $e->getMessage();
} catch (Exception $e) {
echo $e->getMessage();
}

Once an exception has been caught, execution of the script will follow from directly after the last catch block.
To avoid fatal errors from uncaught exceptions, you could wrap your entire application in a try... catch block—which would, however, be rather inconvenient.
Luckily, there is a better solution—PHP allows us to define a “catch-all” function that is automatically called whenever an exception is not handled. This function is set up by calling set_exception_handler():

function handleUncaughtException($e)
{
echo $e->getMessage();
}
set_exception_handler("handleUncaughtException");
throw new Exception("You caught me!");
echo "This is never displayed";


Share this

0 Comment to " PHP Exceptions "

Post a Comment