PHP

Error Handling with Exceptions in PHP 5

Google+ Pinterest LinkedIn Tumblr

In PHP 4 error handling in functions and methods was returned by the return command. Let´s say we would like to connect to a database via MySQLi inside a method or function. If the connection fails an error message and the error code should be displayed. In PHP 4 the error handling would have looked like this:

function connect_to_mysql()
{$mysqli = @new mysqli('localhost', 'username', 'password', 'db_name');
if ($mysqli->connect_errno)
{
return false;}
return true;
}

To find out whether the database connection was successfully established or not we have to check the return value of the function.

if(connect_to_mysql() == false)
{echo "A database connection could not be established.";
die();
}

Say we also have a function for inserting new data into our database or for selecting data from our database we would have to check for each function separately whether an error occurred or not. This is especially important when functions build upon one another.

In PHP 5 the error handling within classes is now possible with exceptions. The class method connect_to_mysql() would look like this in PHP 5 with exceptions:

function connect_to_mysql()
{$mysqli = @new mysqli('localhost', 'username', 'password', 'db_name');
if ($mysqli->connect_errno)
{
throw new Exception('A database connection could not be established.');}
return true;
}

In the script which invokes the class method the explicit validation of the return value is no longer necessary. The execution of the script gets interrupted as soon as an Exception occurs. This is probably one of the main advantages of Exceptions. If you look at the next example you will see that we don´t need to check whether the connection was successfully established before calling the insert_values method. We do not need to validate each return value to ensure no consequential errors occur because the script automatically skips all following operations until the next catch block in case of an Exception.

In order to process the Exception the code which calls the class method needs to be inside a try/catch block.

try
{$someclass->connect_to_mysql();
$someclass->insert_values($arr);
}
catch(Exception $e)
{echo "An error occured.";
}

The output of this Exception might not be as specific and informative as you want it to be. The Exception class can be used to create expressive and informative error messages. It comes with several methods to modify the output. These are getMessage() (Returns the message of the Exception constructor), getCode() (Returns the Exception code), getFile() (Returns the file name in which the Exception occured), getTrace() (Returns an array with the Exception stack trace (read more here)).

So let´s use the Exception methods to create a more effective error message. When an Exception occurs we want to show the file name in which it occurred and the line number. We also want to show the message which was entered into the Exception constructor.

try
{$someclass->connect_to_mysql();
$someclass->insert_values($arr);
}
catch(Exception $e)
{echo "An error occured.\n";
echo "Line Number: ".$e->getLine()."\n";
echo "File Name: ".$e->getFile()."\n";
echo "Error Description: ".$e->getMessage();
}

Now that you know how to create Exceptions there is one more thing you should know about. Imagine you wanted to get data from a file stored on your server, then validate the data and then insert the data into your database. Each of these actions creates different types of errors. In the first case you will have errors which have to do with the file system, for example an error when loading the file or reading it. In the second case you will get errors that will have to do with the validation, for example a wrong data type. In the third case you might have errors when trying to connect to the database or inserting. My point is that we have different kinds of errors, so it would be nice if we could put these errors in separate groups. To do so we can create subclasses from the Exception class.

class FileException extends Exception // Exceptions for errors with the file system
{
}
class ValidateException extends Exception // Exceptions for errors with the validation
{
}
class SQLException extends Exception // Exceptions for errors with the database connection
{
}

If an error occurs in our script we will now be able to use the correct Exception type for it, for example:

function connect_to_mysql()
{$mysqli = @new mysqli('localhost', 'username', 'password', 'db_name');
if ($mysqli->connect_errno)
{
throw new SQLException('A database connection could not be established.');}
return true;
}

We can leave the try/catch block the way it is. catch(Exception $e) will catch any Exception we created even if they are subclasses. If you want to create different error messages for the different subclasses you could also use catch(FileException $e), catch(ValidateException $e) and catch(SQLException $e).

Note that in the Standard PHP Library there are several pre-defined Exceptions which offer the advantage that they are generally known and often used. By using the SPL Exceptions programmers are creating a standard which makes it easier for other programmers to understand your code and work with it. If you would like an overview over the SPL Exceptions check out this instruction on how and when to use which Exception.

I am a frontend and backend web developer who loves building up new projects from scratch. In my blog "Lingulo" me and some guest authors regularly post new tutorials, web design trends or useful resources.

Subscribe
Notify of
guest
2 Comments
Newest
Oldest Most Voted
Inline Feedbacks
View all comments
rayjo
rayjo
9 years ago

its my pleasure #Miss.

rimpy kakeyalia
9 years ago

really helpful,,thnks for sharing dude!!!