Sign In | Subscribe
Start learning today, and be successful in your academic & professional career. Start Today!
Loading video...
This is a quick preview of the lesson. For full access, please Log In or Sign up.
For more information, please see full course syllabus of Advanced PHP
  • Discussion

  • Study Guides

  • Download Lecture Slides

  • Table of Contents

  • Transcription

  • Related Services

Bookmark and Share

Start Learning Now

Our free lessons will get you started (Adobe Flash® required).
Get immediate access to our entire library.

Sign up for

Membership Overview

  • Unlimited access to our entire library of courses.
  • Search and jump to exactly what you want to learn.
  • *Ask questions and get answers from the community and our teachers!
  • Practice questions with step-by-step solutions.
  • Download lesson files for programming and software training practice.
  • Track your course viewing progress.
  • Download lecture slides for taking notes.
  • Learn at your own pace... anytime, anywhere!


  • A try block is a section of code enclosed in curly braces that allows what are known as exceptions to be ‘thrown’ when an error is detected.
  • An exception is an instance of the built-in PHP Exception class, and the throw keyword is used to signal that an error/exception has occurred.
  • When an exception is thrown, execution of code in the try block immediately halts. PHP then looks for a catch block, which is an error handling section of code enclosed in curly braces, immediately following the try block where the exception occurred. If a catch block is found, PHP will run any error handling code contained in the catch block.
  • try/catch blocks are declared using the try and catch keywords.
  • When an Exception object is 'caught' it is assigned to a variable that can be used to access the Exception object between the curly braces of the catch block.
  • The Exception class constructor can take as its first argument an error message to associate with the Exception object. This message can be accessed using the Exception class's instance method getMessage().
  • Once an exception is caught it can be ‘re-thrown’ out of the method it was caught in to be caught by a try/catch block in a calling method.
  • Additional Resources:


Lecture Slides are screen-captured images of important points in the lecture. Students can download and print out these lecture slide images to do practice problems as well as take notes while watching the lecture.

  • Intro 0:00
  • Lesson Overview 0:12
    • Lesson Overview
  • try Blocks 0:44
    • try Blocks Definition
  • catch Blocks 2:03
    • catch Blocks: Definition and Syntax
    • Coding Example: try/catch Blocks
    • When an Exception Object is Caught & Error Handling
  • Exception Class 7:02
    • Exception Class
    • Coding Example: Using try/catch to Catch an Exception Thrown from a Method
  • Re-Throwing Exceptions 16:39
    • Re-Throwing Exceptions
    • Coding Example: Re-throwing an Exception
  • Homework Challenge 20:40
    • Homework Challenge: 1 - 5
  • Homework Challenge (cont.) 22:17
    • Homework Challenge: 6

Transcription: Exceptions

Hello again, and welcome back to's Advanced PHP with MySQL course.0000

In today's lesson, we are going to be introducing the concept of exceptions, which is an object-oriented way of error handling.0005

We are going to introduce what are new structures within PHP code.0014

We are going to be introducing what are known as try/catch blocks.0018

And they are blocks that work in pairs to be able to handle errors in your code.0023

We are going to talk about a built-in class to PHP called the Exception class, which is used to encompass an error.0027

It is a class that essentially represents an error that has occurred.0034

And then, we are going to talk about a concept that will maybe be clearer as we go through it, known as re-throwing exceptions.0037

PHP provides a way to more gracefully handle errors.0046

Right now, the way we do it in code is: you can suppress the error, using the @ operator, and then maybe output a message on your own.0050

Or if you don't catch the error, PHP will just output a very terse, ugly error.0059

Well, what PHP does is provides a functionality called tri/catch blocks.0065

And what a tri block is: it is a section of code that you enclose within curly braces.0071

And when you encounter an error condition within your code (for example, you try to open a file, and you get an error),0079

instead of just outputting an error message there, what you can do is what is called throwing an exception.0085

And what it is, is signaling to the code that an error has occurred.0091

And what you do is use the keyword throw, and you pass it a new instance of the Exception class0096

(which you don't have to include the definition for in your PHP file--it is built into PHP),0105

which typically contains an error message that you are going to include.0110

And then, we are going to see in a second that there is a catch block associated with this that is able to handle these different errors.0114

Let's take a look at that.0122

When an exception is thrown--as soon as an exception is thrown (you encounter it; you throw an error), the code in that try block stops.0126

For example, we were executing some code along here in the try block.0132

We encountered an error, and we threw this exception; any code that was down here no longer gets executed.0136

Instead, what happens is: execution resumes down here to a catch block.0142

A catch block says, "If an Exception object that is of type exception has been thrown..."0147

And here we are throwing an object of type Exception.0153

And you can actually catch other types of exceptions, and that involves inheritance, 0158

which is a little more advanced object-oriented concept that we are not getting into in this course.0161

What the catch block does is: you can assign it to catch different types of exceptions.0168

In this case, we are just going to have it catch the generic Exception class that is provided by PHP.0172

We have some code along here; an error occurred; we throw an exception and set the error message for this Exception object to error.0179

What is going to happen is: code is immediately going to stop.0188

Nothing around here is going to get executed; it is going to go to the test statement; it is going to test if the exception thrown's class type was Exception.0191

Because it was, this is going to match, so what it is going to do is assign it to a value E.0205

And then, it is going to execute a section of code.0210

What this gives you the opportunity to do is: when that error is thrown, you can catch it and perform whatever sort of error handling you want to do.0215

In this particular case, as we will learn about, you are just going to be outputting an error message.0223

Let's take a look at a basic try/catch block.0229

Here, we have just a regular section of PHP code with a try statement.0234

And actually, we are not even testing for an error; to demonstrate the concept, we are just throwing an exception.0239

We are throwing a new instance of the Exception class--we are not even passing it any parameters, which is something you can do.0244

We have an associated catch block with this try block that is going to say, "When an exception is thrown up here, go ahead and catch it."0252

"And then, execute the code within these curly braces."0259

In this case, all we are going to do is output an error message that says an exception has been caught.0263

And because this throw always occurs, this is always going to execute; it is not conditional.0269

Typically, you would have some if statement that would say, "If this condition fails, then throw the exception."0274

In this particular example, we are just throwing it automatically to demonstrate.0279

Let's take a look at the example, and we can see that an exception has been caught.0285

What happened was: PHP ran this code; it got to this line; it says, "OK, this signals an error."0294

"I'm throwing an error; I'm stopping any code; and then, I go down here and process whatever error handling code is associated with that exception."0301

Now, one thing to notice is: let's say down here we had an echo statement, "Hello after."0309

I'm going to call it "Hello before"; so we have a statement before we throw the exception, and an echo statement afterwards.0317

Now, when you throw an exception, execution immediately stops in that code.0329

So, this line is not going to get executed; so if we go ahead and run this code, all we are going to see output is this Hello before, along with our exception here.0333

Let's put a break in there.0340

When we re-run our script, we are going to see Hello before, but we don't see Hello after.0344

And that is because, as soon as the throw occurs, execution of the statements in the try block stops.0349

And it is going to say an exception has been caught.0355

When an exception is caught, it is assigned to a variable that you can access within the curly braces.0362

We saw, in the last example, that it actually looks like this.0367

And here, you can define this in your code with whatever value you want.0380

What that says is, "This is going to catch any exceptions that are thrown within its associated try block,0383

and then it is going to assign the exception that it catches to this variable here that you declared."0390

In this case, we declared it e, so if we wanted to access the different properties and methods of this Exception object0395

(which we are going to talk about in a second), you would do it using this e method (for example, e-->getMessage, which gets its error message).0400

And so, in this catch blocks, this is typically where your error handling occurs and allows you to gracefully exit,0411

rather than having some terse PHP error statement going out to your users.0416

The Exception class has a constructor that can take up to three optional parameters,0425

the first of which is an error message to associate with the Exception object.0429

And then, there are a couple of different methods that the Exception class provides.0433

The first one we are going to talk about is getMessage, and what that one does is: if you set an error message0438

when you create the Exception object, when you pass the error message as the first parameter to the constructor,0443

when you call this getMessage on that instance (so within our catch block, if we called it on e, for example--0449

if that is the value we assign to the exception we are catching), if we call $e-->getMessage,0455

it is going to output whatever message we passed in the constructor to Exception, when we threw the exception.0463

There is also a getFile function that is an instance method of exception, so we would call it $e-->getFile.0469

And that outputs the file where the error occurred.0477

And then, they have this similar function getLine, which tells you the line where an error occurred.0480

If we take a look at an example called fileError.php, we are going to try to open a file called tmp.txt.0486

And it is a file that...let me just double-check to make sure that it...doesn't exist.0492

And the file doesn't exist; and when you try to open the file in read-only mode, it doesn't try to create the file if it doesn't exist.0500

So, when we try to open it, it is going to throw an error.0507

So, we have our error suppression operator here that is going to suppress the error.0509

And then, we can test open to see if an error occurred.0513

If it returns false, then that way we know that we had an error; so we are going to enter this if statement, this conditional statement.0516

And what we are going to say is that we are going to throw an exception.0523

We are going to throw a new exception that has an error message, "There was an error opening the file."0525

What is going to happen is: it is going to get caught as soon as this is thrown.0531

Execution of the code jumps down here to the catch statement.0536

It is going to catch the exception, because it is of the Exception class.0540

It is going to assign it to the variable e, and it is going to execute the code within these curly braces.0544

What we do here is: we are simply taking this exception object that was caught;0550

we are calling the instance method getMessage on it; we are outputting the message, 0554

which is this error message we included in the constructor; and then, we are also making use of 0560

the getLine and getFile instance methods of the Exception class to output where the line and the error occurred.0565

For example, if we go ahead and run this script, we are going to see that there was an error opening the file.0573

"Error occurred on line 27 of" and then it lists the name of the file where the error occurred.0586

And that, again, is because this file doesn't exist, and when you try to open something in read mode, it doesn't try and create the file.0591

So, it is going to generate an error.0598

Let's say, instead, we try to open it in overwrite mode, which automatically creates the file, if it doesn't exist.0599

Then, this isn't going to throw an error; and so now, when we run this file, we should see no output,0608

because open is going to be true, which is going to evaluate to false, so this exception will never get thrown.0612

And so, I will put a little output message here--"after if statement," let's say, so at least we have some output.0620

And that is going to show that this if statement doesn't get executed, and then we output this message.0632

Now, the other thing to note, as well, is: once you reach the end of the try block,0638

if you have not thrown any errors, you don't execute any of the code within the catch blocks.0642

What you would do at this point is: in this case, after we reach this echo statement down here,0647

no exception was thrown--we jump over any catch blocks associated with it, and we beginning executing the next line of code.0652

Maybe let's put another output statement here, "after catch block."0658

What we are going to see, when we run this script, is: open is not going to cause an error, so we are not going to throw an exception.0672

We are going to execute this next line in the try block.0678

Then, we are going to skip over the catch block, because an exception was not thrown.0682

And then, we are going to echo any statements after that.0686

In this case, it is going to say "after catch block."0689

So, when we re-run our script now, we are going to say "after if statement," "after catch block."0690

So, you can see that the exception was not thrown, because there wasn't an error anymore.0696

And then, you can see how the try block continues to execute after a throw statement, if the throw statement never gets executed;0702

and then also that, after you complete all of the statements in a try block, you simply jump down to here.0709

You notice that none of these lines got executed here; we didn't have anything that said an error occurred.0715

That is because an exception was not caught.0720

If you never throw an exception, the code in the catch blocks never gets executed.0724

One other example is: you can throw exceptions from methods, as well.0731

In our case, we have just been throwing them from a first-level PHP script.0742

Well, you can also do it, for example, from object methods.0748

Here is a stripped-down version of the DataFile class we have been using in our web application.0750

It has an access mode, a filename, and then a file handle.0755

You pass into the constructor the name of the file you want to open and the access mode you want to access it as.0759

And then, we define an open function; and the open function tests that the file name is valid, and it attempts to open the file.0765

If it does, it returns true, and the fileHandle property of this class gets set to the handle of the open file.0772

Now, if fopen returns an error, what we are going to do is set fileHandle to null, and we are going to use an exception.0783

And we are going to throw an exception that says there was an error opening the data file.0789

And so, what is going to happen is: when that gets thrown, there is no catch block here, so what it does is0794

jumps to the end of this method and throws the exception to wherever this function was called from.0802

So, if we have a script where we create a new DataFile object, and we try to open it,0807

and this open method is called within a try block, this open method (because it throws an exception that doesn't get caught)--0811

we are going to catch it; it is going to be caught here, because we have a catch block.0818

And then, we are going to be able to output the error message.0823

The other thing is: for example, let's say the filename is not a valid filename.0826

Well, that is also going to be an error; so down here, we can throw an exception with a different error message,0832

saying "instance variable filename needs to be set," because the filename wasn't properly set when creating this.0837

Here is a way that we can use this high-level script that calls this to be able to output two different error messages, depending on which exception occurs.0844

And we do that simply by setting a different value of the error message for our Exception object.0852

For example, if we try to open a data file, and we pass it the filename null, what is going to happen is:0859

when we try to open it, it is going to cause an error, because it is going to test if filename is not equal to null.0865

It is going to turn out false, and so what is going to happen is: it is going to execute this else statement, which is going to throw an exception.0871

If we go and run this script, we can see the error message: "in the open function of dataFile.php, the instance variable filename needs to be set."0878

This is a way you can provide useful information to maybe your users, 0894

or also when you are debugging and things like that, to figure out where things are going wrong.0898

If we had just put 'error,' it is not as informative; so I always encourage you to, when you throw exceptions,0902

and you create error messages, make them as useful and as meaningful as possible, so you can really figure out what is going on.0908

Now, that is as opposed to...let's say, instead, that we pass it a valid filename, tmp.txt, that doesn't exist.0914

But we try to open it in read mode, and as we know, when we call open on a file in read mode that doesn't exist, it is going to throw an error.0929

So, our open method is going to enter this if statement, because the file is not equal to null.0935

But when it tries to open the file, it is going to throw an error.0941

So, what is going to happen is: this if statement is going to return false.0945

We are going to exit the else block, which throws this other exception that has a different error message0949

that says, "There was an error opening the file."0954

If we go back and save this, and we reload our script, we can see that we get a new error: "There was an error opening the data file."0958

That is how you can see how a method can throw an exception that you can catch outside of the class.0966

You don't actually have to catch it in whatever particular block it was defined in.0973

If an exception is thrown within a method, and there is no try/catch block, it will get thrown out to 0977

wherever that method was called from--in this case, in our script, exceptionFromMethod.php.0984

And here, because we have a try/catch block associated with it, we are able to catch it, and then output the error message stored in the Exception object.0990

One thing that you can also do is re-throw exceptions.1001

That means that, if you catch an exception, instead of handling it and just outputting an error message, you can re-throw it.1004

We just learned that you can throw an exception within a method.1011

And if there is no catch block for it, it will be caught in whatever script called it, assuming there is a try/catch block there.1017

Well, what you can also do is: if you have a method that has a try/catch block in it, and it catches an exception,1023

it can throw the error again, which is going to throw it to whatever method caught that.1029

And then, in that case, what you are doing is: it is like this chain of throws, where you can pass it up to wherever you eventually want to handle it.1035

It is more easily understood if we look at an example.1042

Let's say we have this DataFile class that we have created a new function in.1046

It is the same as before, except we have created a new function called appendLine.1050

It is just to append a line to this data file.1054

In this appendLine function, the first thing we do is try to open the data file represented by this class; we call the object method open.1058

Well, we do this within a try block, because we know that this open method can throw an exception.1067

So, in our file, we are going to try to open this file that doesn't exist, so it is going to throw an error.1074

What is going to happen is: this is going to call this open; this open is going to throw an error.1087

Down here, we have a catch block that is going to catch the exception thrown by the open method.1094

And then, instead of outputting an error message here, it is going to re-throw that.1098

And simply, what it does is: you can say throw, and then you can pass it the object that represents that exception.1103

And then, what is going to happen is: whatever method called appendLine has the opportunity to catch that exception.1109

So, in our main script, what we do is declare a new DataFile object that is going to end up causing an error when we try to call appendLine.1116

And then, within a try block, we call the appendLine method with 'Hello, World!'1125

And so, what is going to happen is: we are going to call appendLine.1130

It is going to go into appendLine, and it is going to try to open the file, which is going to go up here.1135

It is going to encounter an error and throw an exception.1139

We are going to catch the exception here.1142

Instead of handling it here, within the object code, we want to handle it, for example, in our script,1144

because that is where we output things to the user.1149

We re-throw it; we have a try/catch block where we call this appendLine.1151

And so now, this exception that occurred two function calls deeper--we catch it in our main script, and then we can output the error message.1156

When we try to append this line, we are going to get the error message that says, in this case,1168

"The file could not be opened," because you can't open this file for reading, because it doesn't exist.1173

If we go and try to run this script, we can see that there is an error opening the data file.1179

We eventually called that method open by calling it from within appendLine, and open threw the exception1188

that appendLine caught, that re-threw it, that our main script caught, that was able to handle it.1197

And what this allows you to do is keep throwing errors down the chain of method calls,1201

until you get to a spot where you want to be able to handle it.1207

In this case, we didn't want to handle the error in this appendLine class, let's say,1209

because typically we want to keep our output separate from our programming logic.1216

So, instead of outputting HTML here in this appendLine function that said there was an error thrown,1222

we are just going to re-throw it up to our main script, which we use to output information to the user.1226

And then, we are going to output the error message there.1232

That is an example of what is known as re-throwing exceptions.1235

For the homework challenge, I want you to create a script that defines a function called divide--1241

just a regular function--not a class function or anything.1246

It takes two parameters that are numbers that are to be divided.1249

And what it is going to do is test if the divisor parameter (which we will have be the second parameter;1253

so the first parameter is going to be the dividend, and the second parameter is going to be the divisor) is equal to 0.1259

If it is equal to 0, I want you to throw an exception using that Exception class.1264

Throw a new exception, and then include an error message in the constructor of Exception that says, "Division by 0 was attempted."1269

That is if it is equal to 0; if the divisor is not equal to 0, then simply divide the dividend by the divisor and return the result.1277

In the same script, after you define the function (instead of defining it in a separate function library, 1286

you can just define at the beginning of the script for this simple example), go ahead and call divide twice:1292

once with the numbers 10 and 5 (so that is going to try to divide 10 by 5).1298

And then, try to call it a second time with 1 and 0 (so it is going to try to divide 1 by 0, which is going to throw an exception).1301

Call both these methods within a try block, and associate a catch block with that try block that will catch an exception.1309

And it is going to catch that divide by 0 exception.1317

And what it is going to do is assign it to a variable, maybe $e.1320

And then, I want you to output the message that is associated with that exception.1325

And that message that is going to be associated with it is what you set when you throw the exception originally, when you call its constructor.1328

And then, when you run the script, you should verify that you see the output of 10 divided by 5 is going to equal 2.1338

And then, instead of seeing another output of 1 divided by 0, you should see your error handling code1343

that says, "An exception has occurred; you tried to divide by 0."1349

That will give you some experience with working with exception handling.1354

That ends today's lesson; thank you for watching look forward to seeing you next time.1358