PHP5 Exception handling
prev | next

try/catch Statement

To implement Exception Handling, try/catch-blocks are used. In code, this looks like the following:

try
{
    $fish->move('walk');
}
catch( Exception $e )
{
    die($e);
}
 
If the movement 'walk' is unknown, fish will throw a NoSuchMovementException, informing the user which chose to let this fish walk, that the fish is unable to do so. This can make sense if there's a large group of animals which can be directed somehow by somebody. So instead of implementing a lot of special move-methods on every single animal, we'll just try if it works, if it doesn't, we'll know. (It would certainly make more sense to check the animals movement-types before letting the user select, to make sure she can only select one of the available types, but that's out of scope ;-)

Realworld applications are fileio, database, memory, etc - if there's a critical operation which shouldn't cause your application to abort, use try/catch to handle the risk. Moreover you'll benefit of more logging possibilities and transparent handling.

Imagine you want to save an uploaded file after inserting the users data into the database (or vice versa). If the operation fails, you might want to rollback the previous operation, to make sure no incomplete datasets are generated. When this happens, you'll simply do a rollback in place, or call a rollback method you keep for these situations.

The use of Exceptions will start to make sense if you have more than one possible place, this Error might occur. - So if you have to implement an update-profile process, you can simply use the exception already defined on the exact same situations. Generalizing this sort of functionality and grouping it, makes sense. Especially on large projects.

In PHP, you can even rethrow exceptions from nested try/catch-blocks, in case you'd like to pass an Exception on to a place you have more control over its handling.

Error Handling in PHP 4

Up to version 4, developers had to use the 'set_error_handler' callback function to implement some sort of generic error handling. This is where Exceptions in PHP5 come into play. Through the use of exceptions, you can do some very nice error reporting, sending stacktraces to yourself and display some meaningfull message to the user.
prev | next