Challenge - 5 Problems
Try-Catch Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of try-catch with exception thrown
What is the output of this PHP code?
PHP
<?php try { echo "Start\n"; throw new Exception("Error happened"); echo "End\n"; } catch (Exception $e) { echo "Caught: " . $e->getMessage() . "\n"; } ?>
Attempts:
2 left
💡 Hint
Remember that code after throw inside try block is not executed.
✗ Incorrect
The code prints "Start" first. Then the exception is thrown, so the line printing "End" is skipped. The catch block runs and prints the exception message.
❓ Predict Output
intermediate2:00remaining
Output when no exception is thrown
What will this PHP code output?
PHP
<?php try { echo "Before\n"; // no exception thrown echo "After\n"; } catch (Exception $e) { echo "Caught\n"; } ?>
Attempts:
2 left
💡 Hint
If no exception is thrown, catch block is skipped.
✗ Incorrect
Since no exception is thrown, both echo statements inside try run normally and catch block is ignored.
❓ Predict Output
advanced2:00remaining
Output with finally block execution
What is the output of this PHP code?
PHP
<?php try { echo "Try block\n"; throw new Exception("Oops"); } catch (Exception $e) { echo "Catch block\n"; } finally { echo "Finally block\n"; } ?>
Attempts:
2 left
💡 Hint
Finally block always runs after try and catch.
✗ Incorrect
The try block runs and throws an exception. The catch block handles it. Finally block runs regardless of exception.
❓ Predict Output
advanced2:00remaining
Output when RuntimeException is thrown
What is the output of this PHP code?
PHP
<?php try { echo "Start\n"; throw new RuntimeException("Runtime error"); } catch (Exception $e) { echo "Caught Exception\n"; } ?>
Attempts:
2 left
💡 Hint
RuntimeException extends Exception, so catch(Exception $e) catches it.
✗ Incorrect
The code prints "Start". Then RuntimeException is thrown, which is caught by catch(Exception $e) since RuntimeException extends Exception. It prints "Caught Exception".
❓ Predict Output
expert3:00remaining
Output with nested try-catch and rethrow
What is the output of this PHP code?
PHP
<?php try { try { echo "Inner try\n"; throw new Exception("Inner error"); } catch (Exception $e) { echo "Inner catch\n"; throw $e; } finally { echo "Inner finally\n"; } } catch (Exception $e) { echo "Outer catch\n"; } finally { echo "Outer finally\n"; } ?>
Attempts:
2 left
💡 Hint
Remember finally blocks run before control leaves the try or catch blocks.
✗ Incorrect
The inner try throws an exception. Inner catch runs and rethrows. Inner finally runs before exception propagates. Outer catch catches the rethrown exception. Outer finally runs last.