Challenge - 5 Problems
Exception Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
What is the output of this PHP code with exception?
Look at the code below. What will it output when run?
PHP
<?php function test() { try { throw new Exception("Error happened"); } catch (Exception $e) { return $e->getMessage(); } } echo test(); ?>
Attempts:
2 left
💡 Hint
The catch block returns the exception message.
✗ Incorrect
The function throws an exception, which is caught immediately. The catch block returns the message 'Error happened', which is then printed.
❓ Predict Output
intermediate2:00remaining
What error does this PHP code raise?
What error will this code produce when run?
PHP
<?php function example() { throw new Exception("Oops"); } example(); echo "Done"; ?>
Attempts:
2 left
💡 Hint
There is no try-catch block to handle the exception.
✗ Incorrect
The function throws an exception but it is not caught, so PHP stops execution and shows an uncaught exception error.
🔧 Debug
advanced2:00remaining
Why does this PHP code cause a fatal error?
This code tries to throw an exception but causes a fatal error. Why?
PHP
<?php try { throw new Exception("Fail"); } catch (Error $e) { echo "Caught error"; } ?>
Attempts:
2 left
💡 Hint
Exception and Error are different classes in PHP.
✗ Incorrect
The catch block only catches Errors, but the thrown object is an Exception, so it is not caught and causes a fatal error.
📝 Syntax
advanced2:00remaining
Which option correctly throws and catches an exception?
Choose the code snippet that correctly throws and catches an exception in PHP.
Attempts:
2 left
💡 Hint
Check for correct syntax: semicolons, parentheses, and method calls.
✗ Incorrect
Option A uses correct try-catch syntax with semicolons and calls getMessage() method properly. Others have syntax errors or wrong method usage.
🚀 Application
expert2:00remaining
How many items are in the array after exception handling?
What is the number of elements in the array $results after running this code?
PHP
<?php $results = []; try { $results[] = 1; throw new Exception("Stop"); $results[] = 2; } catch (Exception $e) { $results[] = 3; } $results[] = 4; print_r($results); ?>
Attempts:
2 left
💡 Hint
Remember that code after throw inside try is skipped.
✗ Incorrect
The array gets 1 before exception, then 3 in catch, then 4 after try-catch. So total 3 elements.