Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to throw an exception in PHP.
PHP
<?php throw new [1]("Something went wrong!"); ?>
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using Error instead of Exception to throw an exception.
Forgetting the 'new' keyword before the class name.
✗ Incorrect
The Exception class is used to throw exceptions in PHP.
2fill in blank
mediumComplete the code to catch an exception in PHP.
PHP
<?php try { // code that may throw } catch ([1] $e) { echo $e->getMessage(); } ?>
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Catching Error instead of Exception when handling exceptions.
Not specifying the exception variable in catch.
✗ Incorrect
The catch block catches exceptions of type Exception or its subclasses.
3fill in blank
hardFix the error in the code to properly handle both errors and exceptions.
PHP
<?php try { // code } catch ([1] $e) { echo $e->getMessage(); } ?>
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Catching only Exception misses Errors.
Using Error alone does not catch Exceptions.
✗ Incorrect
The Throwable interface allows catching both Error and Exception types.
4fill in blank
hardFill both blanks to create a custom exception class that extends the base Exception.
PHP
<?php class MyException extends [1] { public function [2]() { return "Custom exception message."; } } ?>
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Extending Error instead of Exception.
Overriding the constructor instead of getMessage.
✗ Incorrect
Custom exceptions extend Exception and can override getMessage() to customize the message.
5fill in blank
hardFill all three blanks to throw and catch a custom exception properly.
PHP
<?php class CustomError extends [1] {} try { throw new [2](); } catch ([3] $e) { echo "Caught custom error."; } ?>
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Catching a different class than thrown.
Extending Error instead of Exception.
✗ Incorrect
The custom exception class extends Exception. We throw an instance of CustomError and catch it by the same class.