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 PDO Database Security PHP & Databases with PDO

php pdo code challenge 2

how do you wrap up $db object in a try catch block and then set up the catch statement

index.php
<?php

//Place your code below this comment
try {
  $db = new PDO('sqlite::memory');
} catch () {
  $e->getMessage();
  die();
}
?>

I wish I could help you on this, but I have not done this course yet. It will be one of my next, though.

2 Answers

Hi Golide,

Inside the catch parens, we need to choose what kind of exception class to catch and then assign it to a variable, usually $e.

The exception class Exception is a generic, catch-all, exception class - and will catch any error that is thrown in the above try block.

<?php

try {
  // code that may fail
} catch (Exception $e) {
  // for this challenge, we don't need to do anything with $e.
  // just setup the catch block as shown.
}

?>

In a production environment, it may be common to setup several catch blocks - starting with the most specific and ending with the most generic. That would look something like this:

<?php

try {
  // code that may fail
}
catch (PDOException $e) { /* specific error */ }
catch (Exception $e) { /* generic error */ }

?>

Hope this helps,

Cheers

<?php

//Place your code below this comment
try {
  $db = new PDO('sqlite::memory');
  $db -> setAttribute (PDO:: ATTR_ERRMODE, PDO:: ERRMODE_EXCEPTION);
} catch (Exception $e) {

}
?>

MOD: edited to format code

The set attribute line is not required for the challenge.