Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

PHP PHP & Databases with PDO Getting Started With PDO Managing Errors

Nosherwan S.
PLUS
Nosherwan S.
Courses Plus Student 10,707 Points

Question about the try-catch statement.

Hi, I am a little confused about the arguments you send in the catch statement: catch(Exception $e). What I got from the video was that you are creating an object, $e, which is an instance of the "Exception" class? If so, shouldn't it be: catch($e = new Exception()) if that makes any sense. Please let me know what is actually going on inside the brackets of the catch() statement. I've never seen a word with a capital letter inside a functions brackets like "Exception".

1 Answer

Gavin Ralston
Gavin Ralston
28,770 Points

Quoting:

"What I got from the video was that you are creating an object, $e, which is an instance of the 'Exception' class?"

What you're doing with a catch statement is essentially saying "I'm going to catch an exception" which may be generated by whatever you're trying to do in your try block.

So you're not creating anything, you're saying " I'll accept (catch) an Exception object and I'll call it the letter 'e' " and then you access that exception object in your catch block, so you can print full details or whatever.

Think of it like a function or method signature. You're defining the variable and the type (an Exception named 'e'), but some other portion of your code (the try block) will be passing that Exception in as a parameter if there's trouble with whatever dangerous/volatile/risky/error_prone thing you're attempting in the try portion.

That's why you're not creating an exception or anything there. You're actually accepting an Exception handed to you from another part of your code and doing something with it.