PHP Exception Handling in 2022: An Introduction for Beginners

Table of Contents

PHP has an exception control similar to other programming languages, making Exception handling an exciting tool for language users. This article deals with the power and handling of PHP exceptions using simple language aimed at those who do not know anything about the subject.

 

INTRODUCTION

 

As this article is aimed at beginners who know nothing (relatively or absolutely) about exceptions, it is of paramount importance to define what is the Exception in PHP.

 

An exception can be understood as an “error” while executing a PHP script. This “error” can be PHP’s error, such as when trying to include a non-existent file through include (), or an “error” purposely generated by the script, such as when we enter the user or password in a login script.

 

To lighten this, let’s take an example:

 

<? php
        try {
            if (! mysql_connect ('localhost', 'root', '')) {
                throw new Exception ('Connection Error');
            } else {
                echo 'Connection completed';
            }
        } catch (Exception $ e) {
            echo $ e-> getMessage ();
        }
?>

The message “Connection completed” will be displayed if the connection occurs. Otherwise, an exception will be thrown by the line throw new Exception (‘Connection error’); and the “catch” block will be called.

 

In our example, the “catch” block will only print the “Connection Error” message, which was defined in the “throw” command.

 

A beginner might say: is not there a way to do this with “if” blocks? Yes, it is possible, but remember that we are working with a straightforward example. In more elaborate and complex scripts, handling “errors” with “if” blocks can become highly complex.

 

A SLIGHTLY MORE COMPLEX EXAMPLE

 

Now that we know the basics of handling exceptions in PHP, we can work with a slightly more complex example.

 

For this, we will use a PHP / HTML script representing a login system (for learning purposes only).

 

<? php
if ($ _ POST ['action'] == 'login') {// If $ _POST ['action'] is defined ...
    // Validate form fields
    try { // try ..
        if ! $ _ POST [ "user"] oR! $ _ POST [ 'password']) { // if $ _POST [ 'user'] or $ _POST [ 'password'] ... no way defined
            throw new Exception ( 'user or password is blank! '); // get an exception
        }
    } catch (Exception $ e) { //...if try fails, take the exception ...
        echo $ e-> getMessage (); // ... display the message and ...
        goto end; // ..
// ... if validation was positive, try ...
        if ($ _ POST [ 'user']! = 'Guest' OR $ _POST [ 'password']! = '123') { // if user and password do not check ...
            throw new Exception ('User or password does not match'); // ... trigger an exception
        } else { // ... else ...
            echo ... 'Login done!'; // .. write this message
        }
    } catch (Exception $ e) { // if try fails ...
        echo $ e-> getMessage (); // ... display the message and ...
        goto end; // .. go to the end (used only to make sure the login form is displayed)
    }
}
end:// just to make the form appear.
?>
<! DOCTYPE HTML PUBLIC "- // W3C // DTD HTML 4.01 Transitional // EN">
<html>
    <head>
        <meta http-equiv = "Content-Type" content = "text / html; charset = UTF -8 ">
        <title> </ title>
    </ head>
    <body>
        <form method =" post ">
            <fieldset>
                <legend> Login </ legend>
                <label for =" user "> user </ label>
                <input id = "user" name = "user" type = "text" />
                <label for = "password"
                This field is used to activate the login process.
                ->
                <input name = "action" type = "hidden" value = "login" />
            </ fieldset>
            <input type = "submit" value = "Submit" />
            <input type = "reset" value = " Clear "/>
        </ form>
    </ body>
</ html>

As we can see in the code above, if the variable “action” is passed to the script page (via POST), the PHP login script will be executed.

 

if ($ _ POST ['action'] == 'login') {

First, the fields are validated, that is, if the “user” and “password” fields have been passed:

try { // try ..
        if (! $ _ POST ['user'] OR! $ _ POST ['password']) { // if $ _POST ['user'] or $ _POST ['password'] is not defined. ..
            throw new Exception ('Blank user or password!'); // get an exception
        }
    } catch (Exception $ e) { //...if try fails, take the exception ...
        echo $ e-> getMessage (); // ... display the message and ...
        goto end; // .. go to the end (used only to make sure the login form is displayed)
    }

The “try” block contains the code to test if the data has been passed. We use the “if” to decide whether to fire the Exception or not.

 

The “catch” block would display the error message if this occurred.

 

The code “goto end;” is only meant to make the login form always appear. Also, “goto” is essential to stop the execution of the remaining code (in this case, the login part).

 

Let’s take an example of the run stream of “try” and “catch” before proceeding.

 

As it stands, this first part of the script would be executed as follows:

 

1. Execute the code inside the “try.” 1.1. Execution of the if (! $ _ POST [‘user’] OR! $ _ POST [‘password’] line). In this part, if “user” or “password” is undefined, the command inside the “if” is executed. Otherwise, no. 1.2. If “user” or “password” is undefined, throw a new Exception (‘Blank username or password!’); it is executed. From there, any code inside the “try” block will be ignored, going directly to the code inside the “catch.”

 

Illustrating this, if we had the following:

 

try { // try ..
        if (! $ _ POST ['user']) {
            throw new Exception ('Blank user!');
        }
        if (! $ _ POST ['password']) {
            throw new Exception ('Password blank!');
        }
    } catch (Exception $ e) { //... if try fails, take exception ...
        echo $ e-> getMessage (); // ... display the message and ...
        goto end; // .. go to the end (used only to make sure the login form is displayed)
    }

If we sent the form to the blank user, we would only have the message “Blank user” followed by the login form.

 

That is, whenever a new Exception appears, the code will jump directly to the “catch” block corresponding to the “try” being processed.

 

Well, now that we close this parenthesis, we will continue with our initial example.

 

try { // ... if the validation was positive try ...
        if ($ _ POST [ 'user']! = 'guest' OR $ _POST [ 'password']! = '123') { // if user and password does not match ...
            throw new Exception ('User or password does not match'); // ... trigger an exception
        } else { // ... else ...
            echo ... 'Login done!'; // .. write this message
        }
    } catch (Exception $ e) { // if try fails ...
        echo $ e-> getMessage (); // ... display the message and ...
        goto end; // .. go to the end (used only to make sure the login form is displayed)
    }

The above code works exactly like the first “try/catch” block, but the test is performed by “if” to check if the user and password match the configured one.

 

You may still not be convinced that trying/catch is more complex than using “if / else.”

 

IS TRY/CATCH BETTER THAN IF/ELSE?

 

“try/catch” is better than “if/else”?

 

I leave this question to you to answer, even because I understand that each situation should be analyzed as unique. Not always what is good in one case will be in another.

 

So I take the liberty of presenting two solutions to the same problem: one with “try/catch” and another with “if/else.” You, dear reader, decide which is the best.

 

Our didactic problem consists of the need to test three variables:

 

  • $ string1, which may be blank but generate a warning about being blank;
  • $ string2, which must have a minimum length of 5 characters for the script to continue;
  • $ string3, which must be nonzero for the hand to continue.

 

In the end, if the string 2 and 3 tests fail, there should be a failure message. In addition, a message must be printed only if success occurs, and another message must always be printed.

 

First, let’s use the if / else:

 

$ success = true; // need to determine success or failure of code
// testing $ string1
if (strlen ($ string1) == 0) {
    echo '$ string1 is blank!
} else {
    echo $ string1. '<br />';
}
// testing $ string2
if (strlen ($ string2) <5) {
    echo '$ string2 cannot have length of less than 5 characters!';
    $ success = false; // ops! there was an error in the interpretation of the script and it cannot continue
    goto error; // goes to error
} else {
    echo $ string2. '<br />';
}
// testing $ string3
if ($ string3 == 0) {
    echo '$ string3 cannot be zero!
    $ success = false; // ops! An error occurred in the interpretation of the script and it cannot continue to
    goto error; // goes to error
} else {
    echo $ string3. '<br />';
}
if ($ success == true) {
    echo 'This part of the code can only be executed if everything is OK!';
}
error:
if ($ success == false) {
    echo 'General fault';
}
echo 'This part of the code should always be executed!
As the code is very simple, I will not spend our time explaining. So let's get right to the same problem solved with "try/catch";
$ string1 = '';
$ string2 = '1234';
$ string3 = 0;
try {
    try {
        if (strlen ($ string1) == 0) {
            throw new Exception ('$ string1 is blank!');
        } else {
            echo $ string1. '<br />';
        }
    } catch (Exception $ f) {
        echo $ f-> getMessage ();
    }
    try {
        if (strlen ($ string2) <5) {
            throw new Exception ('$ string2 cannot have length less than 5 characters!');
        } else {
            echo $ string2. '<br />';
        }
    } catch (Exception $ g) {
        echo $ g->
        throw new Exception;
    }
    try {
        if ($ string3 == 0) {
            throw new Exception ('$ string3 cannot be zero!');
        } else {
            echo $ string3. '<br />';
        }
    } catch (Exception $ h) {
        echo $ h-> getMessage ();
        throw new Exception;
    }
    echo 'This part of the code can only be executed if everything is OK! <br />';
} catch (Exception $ e) {
    $ e-> getMessage ();
}
echo 'This part of the code should always be executed!

Now it is up to you, dear reader, to decide what is best. I only recommend that, whenever possible, avoid the mess. The exception handling of PHP is not for nothing. If it exists, it should be used where applicable.

 

CONCLUSION

 

Like all good texts, this one also has a summary in conclusion.

 

If you had to highlight three critical points in the text, they would be as follows:

 

  1. The exception handling of PHP is quite similar to other languages, making it easier to know other programming languages, but it starts in PHP;
  2. The operation is simple: Everything inside the “try” block is executed. If an exception is called by “throw,” from that point, the script passes to the corresponding “catch” block, ignoring all the rest of the “try”;
  3. Although the use of if/else and other flow controls may seem more manageable or less complicated, sometimes they can become an awful mess that even the original script programmer cannot understand.

 

Very well, dear reader. If you have come this far, I hope you have understood how it works and how good PHP exception handling is.

 

I remind everyone that this is a didactic article for beginners, so more advanced questions or techniques should be left for future articles.

 

Fully Managed WordPress Hosting

Nestify’s AWS powered dedicated CPU servers keep your sites fast, secure, and always up to date.

Want faster WordPress?

WordPress Speed Optimization

Try our AWS powered WordPress hosting for free and see the difference for yourself.

No Credit Card Required.

Whitelabel Web Hosting Portal Demo

Launching WordPress on AWS takes just one minute with Nestify.

Launching WooCommerce on AWS takes just one minute with Nestify.