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 trialMUZ140644 Golide Makhosi
3,738 Pointsphp pdo code challenge 2
how do you wrap up $db object in a try catch block and then set up the catch statement
<?php
//Place your code below this comment
try {
$db = new PDO('sqlite::memory');
} catch () {
$e->getMessage();
die();
}
?>
2 Answers
Robert Richey
Courses Plus Student 16,352 PointsHi 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
MUZ141094 Smart Mashegede
3,335 Points<?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
Ted Sumner
Courses Plus Student 17,967 PointsThe set attribute line is not required for the challenge.
Ted Sumner
Courses Plus Student 17,967 PointsTed Sumner
Courses Plus Student 17,967 PointsI wish I could help you on this, but I have not done this course yet. It will be one of my next, though.