PHP Error Checking

Jul 31, 2012
PHP
134 Shares
By

“Just when you think you’ve made something foolproof, God makes a better brand of fool.”

This maxim of manufacturing also applies to software development, especially on a highly accessible technology like web applications. As much as programmers attempt to anticipate every possible action or combination of actions that a user can take when encountering a web application, no one can foresee them all. When the user takes an unanticipated course of action and “breaks” the application, the software needs to catch them before they fall.

Die() Function

One of the techniques that early PHP programmers used to catch errors was the “die” function. When the program would “die”, this function stops the script and displays an error message.

<?php
if(!file_exists("hello_world.txt")){
   die("File not found");
}
else
{
   $file=fopen("hello_world.txt","r");
   echo(“Hello World file found”);
}
?>

Without the die function, the program would return a specific error message, but not one that users could readily understand:

Warning: fopen(hello_world.txt) [function.fopen]: failed to open stream:No such file or directory in C:\wwwroot\developer_drive\file_opener.php on line 2

Exception Handling

As with other C-based languages (C#, Java, etc.), PHP 5 has a technique for catching exceptions. The keywords “try”, “throw” and “catch” find exceptions and enable better error handling.

Try: Any function that employs the use of an exception to handle errors should be in a “try” block. If the exception is not triggered, the rest of the script will continue executing as written. If the exception is triggered, the exception is said to be “thrown”.
Throw: The “throw” block triggers an exception. For each “throw” block, there must be one or more “catch” blocks.
Catch: The “catch” block retrieves an exception and instantiates an object that holds the exception data.

<?php
try {
    $error = 'Throw this error';
    throw new Exception($error);
// Code following an exception is not executed.
    echo 'This line is ignored';
}
catch (Exception $e) {
    echo 'Exception caught: ',  $e->getMessage(), "\n";
}
// Continue execution
echo 'This line is executed.';
?>

The Exception class that the catch block creates contains several methods:
getMessage()- displays message of exception
getFile() – finds error source filename
getLine() – finds error source line
getCode() – displays code of exception
getTrace() – creates an array of the backtrace()
getTraceAsString() – formats string of trace array

Trigger Error

In most cases, programmers attempt to avoid errors. In some instances, however, developers may want to test their error handling capabilities.  The “trigger_error” function throws an error message when the program encounters an error:

<?php
$text= “Hello”;
if ($text !== “Goodbye”){
trigger_error(“Say Goodbye. Error Triggered.”);
}
?>

Error Messages

Not only do applications have to catch errors before the user encounters them, they must present the reason for the error in a way that the user will understand why it “broke”.

Error messages should always be easy to read for the users; these message allows the user to remain confident that the application can be fixed.  The error messages also help developers chase down potential problems.

Remember, confused users can become angry users, and a user’s anger can lead to a developer’s impending unemployment.

Author: Gerald Hanks
Gerald Hanks has been involved in web development applications since 1996. He has designed applications with JavaScript, ASP.NET and PHP, as well as building databases in MS SQL Server and MySQL. He lives in Houston, Texas.
  • Trevor Geene

    I’ve never run into a situation where the try/catch method was necessary. Would you be able to give a real world example as to where this would be needed?

    • http://blog.alexvernacchia.com Alex Vernacchia

      You would use try/catch when you throw an exception as an error and you want to don’t want to break your application.

      For example, if I have a User class that requires specific parameters to be instantiated, and the correct ones aren’t provided when it is instantiated, you can throw an exception.

      When you initialize the User class, you would use a try/catch statement to see if an exception was thrown (if the proper parameters were not used), and if it was handle it gracefully (store it in a variable and display it later) and not have your whole application stop functioning because of this exception.

  • http://www.baytechwebdesignsem.com/ Baytech Web Design

    Great post i like it

  • http://twitter.com/paulund_ Paulund

    It’s also worth noting that it’s good practice to log most caught exceptions, this helps when bugs are raised you can look back at the logs to see what exceptions were caught. It makes it so much easier to debug and recreate a bug.

  • thomas

    Great, I
    hope you do! :)