Bird
Raised Fist0
PHPprogramming~20 mins

Error handling with PDO exceptions in PHP - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
PDO Exception Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
What is the output when a PDO exception occurs?
Consider the following PHP code that tries to connect to a database with wrong credentials. What will be the output?
PHP
<?php
try {
  $pdo = new PDO('mysql:host=localhost;dbname=testdb', 'wronguser', 'wrongpass');
  echo "Connected successfully";
} catch (PDOException $e) {
  echo "Connection failed: " . $e->getMessage();
}
?>
AConnected successfully
BFatal error: Uncaught PDOException: SQLSTATE[HY000] [1045] Access denied for user 'wronguser'@'localhost' (using password: YES)
CConnection failed: SQLSTATE[HY000] [1045] Access denied for user 'wronguser'@'localhost' (using password: YES)
DNo output
Attempts:
2 left
💡 Hint
Think about what happens when the connection fails and how exceptions are caught.
❓ Predict Output
intermediate
2:00remaining
What error is raised when accessing a non-existent PDO attribute?
What error will the following PHP code produce?
PHP
<?php
$pdo = new PDO('sqlite::memory:');
echo $pdo->getAttribute(PDO::ATTR_NON_EXISTENT);
?>
ANULL
BWarning: PDO::getAttribute() expects parameter 1 to be integer, string given
CNotice: Undefined class constant 'ATTR_NON_EXISTENT'
DFatal error: Uncaught Error: Undefined class constant 'ATTR_NON_EXISTENT'
Attempts:
2 left
💡 Hint
Check if the constant exists in the PDO class.
🔧 Debug
advanced
2:00remaining
Why does this PDO exception not get caught?
Examine the code below. Why does the exception not get caught by the catch block?
PHP
<?php
try {
  $pdo = new PDO('mysql:host=localhost;dbname=testdb', 'wronguser', 'wrongpass');
  $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  $pdo->query('INVALID SQL');
} catch (PDOException $e) {
  echo "Error caught: " . $e->getMessage();
}
?>
AThe exception is not caught because the error mode is set after the connection attempt.
BThe exception is not caught because query() does not throw exceptions.
CThe exception is caught and the message is printed.
DThe code has a syntax error and does not run.
Attempts:
2 left
💡 Hint
Think about when the error mode is set and when exceptions are thrown.
❓ Predict Output
advanced
2:00remaining
What is the output of this PDO exception handling code?
What will this PHP code output?
PHP
<?php
try {
  $pdo = new PDO('sqlite::memory:');
  $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  $pdo->exec('CREATE TABLE test(id INTEGER PRIMARY KEY)');
  $pdo->exec('INSERT INTO test(id) VALUES(1)');
  $pdo->exec('INSERT INTO test(id) VALUES(1)');
  echo "Insert succeeded";
} catch (PDOException $e) {
  echo "Insert failed: " . $e->getMessage();
}
?>
AInsert failed: SQLSTATE[23000]: Integrity constraint violation: 19 UNIQUE constraint failed: test.id
BNo output
CFatal error: Uncaught PDOException: SQLSTATE[23000]: Integrity constraint violation
DInsert succeeded
Attempts:
2 left
💡 Hint
Think about what happens when you insert a duplicate primary key with exceptions enabled.
🧠 Conceptual
expert
3:00remaining
Which option correctly demonstrates catching and rethrowing a PDO exception?
You want to catch a PDOException, log the error message, and then rethrow it to be handled elsewhere. Which code snippet does this correctly?
A
&lt;?php
try {
  $pdo = new PDO('mysql:host=localhost;dbname=testdb', 'user', 'pass');
} catch (PDOException $e) {
  throw $e;
  error_log($e-&gt;getMessage());
}
?&gt;
B
&lt;?php
try {
  $pdo = new PDO('mysql:host=localhost;dbname=testdb', 'user', 'pass');
} catch (PDOException $e) {
  error_log($e-&gt;getMessage());
  throw $e;
}
?&gt;
C
&gt;?
}
;e$ worht  
;))(egasseMteg&gt;-e$(gol_rorre  
{ )e$ noitpecxEODP( hctac }
;)'ssap' ,'resu' ,'bdtset=emanbd;tsohlacol=tsoh:lqsym'(ODP wen = odp$  
{ yrt
php?&lt;
D
&lt;?php
try {
  $pdo = new PDO('mysql:host=localhost;dbname=testdb', 'user', 'pass');
} catch (PDOException $e) {
  error_log($e-&gt;getMessage());
}
throw $e;
?&gt;
Attempts:
2 left
💡 Hint
Remember that code after throw is not executed and variables must be in scope.

Practice

(1/5)
1. What is the main purpose of using try and catch blocks when working with PDO exceptions in PHP?
easy
A. To create new database tables
B. To handle database errors without stopping the entire program
C. To automatically fix SQL syntax errors
D. To speed up database queries

Solution

  1. Step 1: Understand the role of try-catch

    The try block runs code that might cause an error, and catch handles that error safely.
  2. Step 2: Relate to PDO exceptions

    PDO exceptions occur on database errors; using try-catch prevents the program from stopping abruptly.
  3. Final Answer:

    To handle database errors without stopping the entire program -> Option B
  4. Quick Check:

    try-catch handles errors safely = D [OK]
Hint: Try-catch blocks catch errors to keep programs running [OK]
Common Mistakes:
  • Thinking try-catch speeds up queries
  • Believing it fixes SQL errors automatically
  • Confusing error handling with database creation
2. Which of the following is the correct way to set PDO to throw exceptions on errors?
easy
A. $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT);
B. $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
C. $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
D. $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_IGNORE);

Solution

  1. Step 1: Identify PDO error modes

    PDO supports error modes: SILENT, WARNING, EXCEPTION, and IGNORE (not standard).
  2. Step 2: Choose the mode that throws exceptions

    PDO::ERRMODE_EXCEPTION makes PDO throw exceptions on errors.
  3. Final Answer:

    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); -> Option C
  4. Quick Check:

    Exception mode = PDO::ERRMODE_EXCEPTION = B [OK]
Hint: Use ERRMODE_EXCEPTION to get PDO exceptions [OK]
Common Mistakes:
  • Using ERRMODE_SILENT which hides errors
  • Confusing ERRMODE_WARNING with exceptions
  • Using non-existent ERRMODE_IGNORE
3. What will be the output of this PHP code?
$pdo = new PDO('sqlite::memory:');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
try {
    $pdo->exec('CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT)');
    $pdo->exec('INSERT INTO users (id, name) VALUES (1, "Alice")');
    $pdo->exec('INSERT INTO users (id, name) VALUES (1, "Bob")');
    echo "Insert successful";
} catch (PDOException $e) {
    echo "Error: " . $e->getMessage();
}
medium
A. Insert successful
B. Syntax error in SQL statement
C. No output
D. Error: SQLSTATE[23000]: Integrity constraint violation: UNIQUE constraint failed: users.id

Solution

  1. Step 1: Understand the code flow

    The code creates a table with a primary key on 'id' and inserts two rows with the same id=1.
  2. Step 2: Identify the error

    Inserting duplicate primary keys causes an integrity constraint violation, triggering a PDOException.
  3. Final Answer:

    Error: SQLSTATE[23000]: Integrity constraint violation: UNIQUE constraint failed: users.id -> Option D
  4. Quick Check:

    Duplicate primary key causes exception = C [OK]
Hint: Duplicate primary keys cause PDOException errors [OK]
Common Mistakes:
  • Expecting 'Insert successful' despite duplicate keys
  • Thinking it's a syntax error
  • Ignoring exception handling output
4. Identify the error in this PHP code snippet that uses PDO exceptions:
try {
    $pdo = new PDO('mysql:host=localhost;dbname=testdb', 'user', 'pass');
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $pdo->exec('INVALID SQL');
} catch (PDOException $e) {
    echo 'Error: ' . $e->getMessage();
}
medium
A. SQL statement is invalid causing exception
B. Error mode is not set to exceptions
C. PDO connection string is incorrect
D. Missing catch block for exceptions

Solution

  1. Step 1: Check PDO connection and error mode

    The connection string and error mode setting are correct for throwing exceptions.
  2. Step 2: Analyze the SQL statement

    The SQL statement 'INVALID SQL' is not valid SQL, so it triggers a PDOException.
  3. Final Answer:

    SQL statement is invalid causing exception -> Option A
  4. Quick Check:

    Invalid SQL causes exception = A [OK]
Hint: Invalid SQL triggers PDOException if error mode set [OK]
Common Mistakes:
  • Assuming connection string is wrong
  • Forgetting error mode is set correctly
  • Thinking catch block is missing
5. You want to safely insert user data into a database using PDO and handle errors with exceptions. Which of the following code snippets correctly implements this with prepared statements and exception handling?
hard
A. try { $pdo = new PDO($dsn, $user, $pass); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $stmt = $pdo->prepare('INSERT INTO users (name, email) VALUES (:name, :email)'); $stmt->execute([':name' => $name, ':email' => $email]); echo 'User added'; } catch (PDOException $e) { echo 'Error: ' . $e->getMessage(); }
B. $pdo = new PDO($dsn, $user, $pass); $stmt = $pdo->query('INSERT INTO users (name, email) VALUES ($name, $email)'); echo 'User added';
C. try { $pdo = new PDO($dsn, $user, $pass); $stmt = $pdo->prepare('INSERT INTO users (name, email) VALUES (?, ?)'); $stmt->execute([$name, $email]); echo 'User added'; } catch (Exception $e) { echo 'Error'; }
D. try { $pdo = new PDO($dsn, $user, $pass); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING); $pdo->exec('INSERT INTO users (name, email) VALUES ("$name", "$email")'); echo 'User added'; } catch (PDOException $e) { echo 'Error: ' . $e->getMessage(); }

Solution

  1. Step 1: Check for proper error mode setting

    try { $pdo = new PDO($dsn, $user, $pass); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $stmt = $pdo->prepare('INSERT INTO users (name, email) VALUES (:name, :email)'); $stmt->execute([':name' => $name, ':email' => $email]); echo 'User added'; } catch (PDOException $e) { echo 'Error: ' . $e->getMessage(); } sets PDO::ATTR_ERRMODE to ERRMODE_EXCEPTION, enabling exception handling.
  2. Step 2: Verify use of prepared statements and parameter binding

    try { $pdo = new PDO($dsn, $user, $pass); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $stmt = $pdo->prepare('INSERT INTO users (name, email) VALUES (:name, :email)'); $stmt->execute([':name' => $name, ':email' => $email]); echo 'User added'; } catch (PDOException $e) { echo 'Error: ' . $e->getMessage(); } uses prepared statements with named parameters and executes safely with user data.
  3. Step 3: Confirm exception handling

    try { $pdo = new PDO($dsn, $user, $pass); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $stmt = $pdo->prepare('INSERT INTO users (name, email) VALUES (:name, :email)'); $stmt->execute([':name' => $name, ':email' => $email]); echo 'User added'; } catch (PDOException $e) { echo 'Error: ' . $e->getMessage(); } catches PDOException and outputs the error message, providing safe error handling.
  4. Final Answer:

    try { $pdo = new PDO($dsn, $user, $pass); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $stmt = $pdo->prepare('INSERT INTO users (name, email) VALUES (:name, :email)'); $stmt->execute([':name' => $name, ':email' => $email]); echo 'User added'; } catch (PDOException $e) { echo 'Error: ' . $e->getMessage(); } -> Option A
  5. Quick Check:

    Prepared + ERRMODE_EXCEPTION + try-catch = A [OK]
Hint: Use prepared statements with ERRMODE_EXCEPTION and try-catch [OK]
Common Mistakes:
  • Not setting error mode to exceptions
  • Using query() with unescaped variables
  • Catching generic Exception instead of PDOException
  • Using ERRMODE_WARNING which doesn't throw exceptions
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard