Challenge - 5 Problems
PHP Error vs Exception Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of error and exception handling
What will be the output of this PHP code snippet?
PHP
<?php function test() { try { throw new Exception("Exception caught"); } catch (Error $e) { echo "Error caught"; } catch (Exception $e) { echo $e->getMessage(); } } test();
Attempts:
2 left
💡 Hint
Remember that Exception and Error are different classes in PHP and catch blocks handle exceptions based on type.
✗ Incorrect
The thrown Exception is caught by the catch block for Exception, so it prints 'Exception caught'. The catch block for Error is skipped because the thrown object is not an Error.
❓ Predict Output
intermediate2:00remaining
Behavior of uncaught Error
What happens when this PHP code runs?
PHP
<?php function test() { try { undefinedFunction(); } catch (Exception $e) { echo "Exception caught"; } } test();
Attempts:
2 left
💡 Hint
Undefined functions cause Errors, not Exceptions.
✗ Incorrect
Calling an undefined function throws an Error, which is not caught by the catch block for Exception, so a fatal error occurs.
🔧 Debug
advanced2:00remaining
Identify the error type caught
What type of error or exception is caught by this code?
PHP
<?php try { $arr = []; $arr[5](); } catch (Error $e) { echo get_class($e); } catch (Exception $e) { echo get_class($e); }
Attempts:
2 left
💡 Hint
Accessing an undefined array index triggers a specific error type in PHP 7+.
✗ Incorrect
Accessing an undefined array index throws an Error of type Error, not Exception or ErrorException.
📝 Syntax
advanced2:00remaining
Which catch block order is correct?
Given that Error and Exception are both throwable in PHP, which catch block order will NOT cause a fatal error?
PHP
try { // some code } catch (___) { // handle } catch (___) { // handle }
Attempts:
2 left
💡 Hint
More specific exceptions must be caught before more general ones.
✗ Incorrect
Error and Exception both implement Throwable. Catching Error before Exception is correct because they are siblings. Catching Throwable before Exception causes unreachable code error.
🧠 Conceptual
expert2:00remaining
Difference between Error and Exception in PHP
Which statement best describes the difference between Error and Exception in PHP?
Attempts:
2 left
💡 Hint
Think about what kind of problems each class represents and how PHP treats them.
✗ Incorrect
Errors represent serious problems like engine failures or type errors, while Exceptions are for user-defined or runtime issues that can be caught and handled by the program.