Further PHP try / catch PHP 5

A try / catch block is meant to catch exceptions.  An exception would be something like divide by zero which causes a program exception and this can be caught.

An error on the other hand is not usually recoverable.  An example of an error would be forgetting to place a ; at the end of a line or not enclosing a string with ” marks.

In the case of divide by zero, if you use a try / catch block, program execution will continue because you have caught the exception.

Each try must have at least one corresponding catch block.  You can have multiple catch blocks to catch different classes of exceptions.

When an exception is thrown, the code following the statement will not be executed and PHP will then attempt to find the first matching catch block.

The general form of a try / catch block is :

$a = 1;
$b = 0;
$c = $a / $b;
catch (Exception $e)

Other functions of the exception class are :

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

You may extend the exception class to create your own custom exceptions and the use them as multiple catch blocks to catch different classes of exception as shown in the following code :


//Extending the exception class

class WidgetNotFoundException extends Exception {}

function use_widget($widget_name) {
$widget = find_widget($widget_name);

if (!$widget) {
throw new WidgetNotFoundException(t(‘Widget %widget not found.’, array(‘%widget’ => $widget_name)));

//The try / catch block

try {
$widget = ‘thingie’;
$result = use_widget($widget);

// Continue processing the $result.
// If an exception is thrown by use_widget(), this code never gets called.
catch (WidgetNotFoundException $e) {
// Error handling specific to the absence of a widget.
catch (Exception $e) {
// Generic exception handling if something else gets thrown.
watchdog(‘widget’, $e->getMessage(), WATCHDOG_ERROR);


Leave a Reply