Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to catch an exception in PHP.
PHP
<?php try { // Some code that may throw an exception } catch (Exception [1]) { echo 'Error caught!'; } ?>
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Forgetting the dollar sign before the variable name.
Using a variable name not declared in the catch block.
✗ Incorrect
In PHP, the catch block requires a variable to hold the exception object, commonly $e.
2fill in blank
mediumComplete the code to throw an exception when a condition is met.
PHP
<?php if ($age < 18) { [1] new Exception('Age must be 18 or older'); } ?>
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'raise' instead of 'throw'.
Using 'catch' or 'try' incorrectly.
✗ Incorrect
In PHP, to trigger an exception, you use the throw keyword.
3fill in blank
hardFix the error in the code to properly handle exceptions.
PHP
<?php try { $file = fopen('data.txt', 'r'); if (!$file) { [1] new Exception('File not found'); } } catch (Exception $e) { echo $e->getMessage(); } ?>
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'raise' which is not valid in PHP.
Using 'catch' inside the try block.
✗ Incorrect
The code must use throw to raise an exception inside the try block.
4fill in blank
hardFill both blanks to create a custom exception class and throw it.
PHP
<?php class [1] extends Exception {} try { [2] new [1]('Custom error occurred'); } catch ([1] $e) { echo $e->getMessage(); } ?>
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'catch' instead of 'throw' to raise the exception.
Not extending the Exception class.
✗ Incorrect
You define a custom exception class by extending Exception. Then you throw an instance of it.
5fill in blank
hardFill all three blanks to handle multiple exceptions properly.
PHP
<?php try { // Some code } catch ([1] $e) { echo 'First error: ' . $e->getMessage(); } catch ([2] $e) { echo 'Second error: ' . $e->getMessage(); } catch ([3] $e) { echo 'General error: ' . $e->getMessage(); } ?>
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Catching the general Exception first, which prevents specific catches.
Using 'Error' instead of 'Exception' for general catch.
✗ Incorrect
Use specific exception classes first, then the general Exception class last to catch all other exceptions.