Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to ensure the finally block always executes.
PHP
<?php try { echo "Try block executed.\n"; } [1] { echo "Catch block executed.\n"; } finally { echo "Finally block executed.\n"; } ?>
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Omitting the catch block causes syntax errors.
Using an incorrect catch syntax.
✗ Incorrect
The catch (Exception $e) block catches exceptions and allows the finally block to execute afterward.
2fill in blank
mediumComplete the code to throw an exception inside the try block.
PHP
<?php try { throw new [1]("Error occurred."); } catch (Exception $e) { echo $e->getMessage(); } finally { echo "\nFinally block runs."; } ?>
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using a class that is not an Exception or subclass.
Forgetting the 'new' keyword.
✗ Incorrect
Throwing a new Exception inside the try block triggers the catch block.
3fill in blank
hardFix the error in the catch block syntax.
PHP
<?php try { echo "Inside try.\n"; } catch [1] { echo "Caught exception.\n"; } finally { echo "Finally block executed.\n"; } ?>
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Omitting the variable name in catch parentheses.
Using incorrect parentheses syntax.
✗ Incorrect
The catch block must specify the exception type and a variable to hold it, like (Exception $e).
4fill in blank
hardFill both blanks to create a finally block that always runs after try and catch.
PHP
<?php try { echo "Trying...\n"; } catch (Exception $e) { echo "Exception caught.\n"; } [1] { echo "[2] block executed.\n"; } ?>
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'catch' instead of 'finally' for the last block.
Omitting the finally block.
✗ Incorrect
The finally block runs after try and catch blocks regardless of exceptions.
5fill in blank
hardFill all three blanks to handle an exception and ensure the finally block runs.
PHP
<?php try { throw new [1]("Error!"); } catch ([2] $e) { echo $e->getMessage(); } [3] { echo "\nFinally block executed."; } ?>
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Mismatching exception types in throw and catch.
Using 'catch' instead of 'finally' for the last block.
✗ Incorrect
Throw an Exception, catch it with Exception $e, and use finally to run code always.