0
0
PHPprogramming~10 mins

Why error handling matters in PHP - Test Your Understanding

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

Complete 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'
A$error
B$ex
C$e
D$exception
Attempts:
3 left
💡 Hint
Common Mistakes
Forgetting the dollar sign before the variable name.
Using a variable name not declared in the catch block.
2fill in blank
medium

Complete 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'
Athrow
Bcatch
Craise
Dtry
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'raise' instead of 'throw'.
Using 'catch' or 'try' incorrectly.
3fill in blank
hard

Fix 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'
Athrow
Bcatch
Ctry
Draise
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'raise' which is not valid in PHP.
Using 'catch' inside the try block.
4fill in blank
hard

Fill 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'
AMyException
Bthrow
Ccatch
DException
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'catch' instead of 'throw' to raise the exception.
Not extending the Exception class.
5fill in blank
hard

Fill 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'
AFirstException
BSecondException
CException
DError
Attempts:
3 left
💡 Hint
Common Mistakes
Catching the general Exception first, which prevents specific catches.
Using 'Error' instead of 'Exception' for general catch.