0
0
PHPprogramming~10 mins

Error vs Exception in PHP - Interactive Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete 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'
AError
BException
CThrowable
DRuntimeException
Attempts:
3 left
💡 Hint
Common Mistakes
Using Error instead of Exception to throw an exception.
Forgetting the 'new' keyword before the class name.
2fill in blank
medium

Complete 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'
AException
BError
CThrowable
DRuntimeException
Attempts:
3 left
💡 Hint
Common Mistakes
Catching Error instead of Exception when handling exceptions.
Not specifying the exception variable in catch.
3fill in blank
hard

Fix 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'
AException
BError
CThrowable
DErrorException
Attempts:
3 left
💡 Hint
Common Mistakes
Catching only Exception misses Errors.
Using Error alone does not catch Exceptions.
4fill in blank
hard

Fill 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'
AException
B__construct
CgetMessage
DError
Attempts:
3 left
💡 Hint
Common Mistakes
Extending Error instead of Exception.
Overriding the constructor instead of getMessage.
5fill in blank
hard

Fill 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'
AException
BCustomError
DError
Attempts:
3 left
💡 Hint
Common Mistakes
Catching a different class than thrown.
Extending Error instead of Exception.