Learn

So, how did you do with all those exercises? If your experience was anything like ours, you probably didn’t get everything right the first time. In fact, to let you in on a little secret, even the best programmers make mistakes.

And sometimes, even when our code works well, there can be issues beyond our control. For example, PHP might be unable to connect to the database, or a third-party service we rely on, such as a payment processor or an email delivery service, might be down.

How do we handle such problems? PHP provides us with exception handling, which lets us rescue our program from such situations and tell it what to do next.

We do this using try/catch blocks.

We start with a try block, which tells the PHP interpreter to try executing some code:

try { // Charge user's credit card // Add transaction to the database // Email receipt to user }

If an exception is thrown, it will be caught, and PHP will immediately begin running code in the catch block.

// When an exception occurs catch (Exception $e) { // Rollback transaction // Add error to the log // Notify user that an error occurred }

The argument to the catch block is the exception object which will catch all exceptions thrown. Assigning the exception object to the variable $e lets us call several useful methods to help us troubleshoot the exception.

// Echo out the exception object's message which often has useful information echo $e->getMessage();

Instructions

1.

Let’s apply a try/catch block to our database connection to ensure we catch and handle any errors.

Start by creating a DSN to connect to PostgreSQL. We assign these variables before the try block since the assignments will not throw exceptions.

Don’t worry about the error in the output terminal, we’ll fix it at the final checkpoint.

2.

Next, add a try and catch block around the database connection.

3.

What happens when you try running the code? It breaks. To find out what’s broken, echo the exception object’s message.

4.

PHP is having trouble connecting to the database server. That is because the value of $hostname is incorrect.

On line 4, set $hostname to /tmp for the connection to work.

Take this course for free

Mini Info Outline Icon
By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.

Or sign up using:

Already have an account?