Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to catch an exception.
PHP
<?php try { // code that may throw an exception } 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 an exception class.
Using 'Error' when catching exceptions.
✗ Incorrect
The Exception class is used to catch exceptions in PHP.
2fill in blank
mediumComplete the code to catch a specific exception type.
PHP
<?php try { // code that may throw an exception } catch ([1] $e) { echo 'Invalid argument: ' . $e->getMessage(); } ?>
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using the generic Exception class instead of the specific one.
✗ Incorrect
InvalidArgumentException is used to catch invalid argument errors specifically.
3fill in blank
hardFix the error in the catch block to catch multiple exceptions separately.
PHP
<?php try { // code that may throw exceptions } catch (InvalidArgumentException $e) { echo 'Invalid argument: ' . $e->getMessage(); } catch ([1] $e) { echo 'Runtime error: ' . $e->getMessage(); } ?>
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using the generic Exception class again.
Using Error which is not an exception.
✗ Incorrect
The second catch block should catch RuntimeException to handle runtime errors separately.
4fill in blank
hardFill both blanks to catch multiple exceptions and handle them differently.
PHP
<?php try { // code that may throw exceptions } catch ([1] $e) { echo 'Argument error: ' . $e->getMessage(); } catch ([2] $e) { echo 'General error: ' . $e->getMessage(); } ?>
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Swapping the order of exceptions.
Using Error instead of Exception.
✗ Incorrect
The first catch block handles InvalidArgumentException, the second handles the general Exception.
5fill in blank
hardFill all three blanks to catch multiple exceptions and print different messages.
PHP
<?php try { // code that may throw exceptions } catch ([1] $e) { echo 'Argument error: ' . $e->getMessage(); } catch ([2] $e) { echo 'Runtime error: ' . $e->getMessage(); } catch ([3] $e) { echo 'Other error: ' . $e->getMessage(); } ?>
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Catching Exception before specific exceptions.
Using Error instead of Exception.
✗ Incorrect
The code catches InvalidArgumentException, then RuntimeException, then any other Exception.