0
0
PHPprogramming~10 mins

Try-catch execution flow in PHP - Interactive Code Practice

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

Complete the code to catch exceptions.

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'
AError
BThrowable
CException
DErrorException
Attempts:
3 left
💡 Hint
Common Mistakes
Using a class that does not represent exceptions will cause a fatal error.
Forgetting to specify a class in the catch block.
2fill in blank
medium

Complete the code to throw an exception.

PHP
<?php
function checkAge($age) {
    if ($age < 18) {
        throw new [1]("Age must be at least 18.");
    }
    return true;
}
?>
Drag options to blanks, or click blank then click option'
AException
BErrorException
CThrowable
DError
Attempts:
3 left
💡 Hint
Common Mistakes
Using a class that is not throwable will cause an error.
Forgetting to use the 'new' keyword when throwing an exception.
3fill in blank
hard

Fix the error in the catch block to properly catch exceptions.

PHP
<?php
try {
    throw new Exception("Error occurred.");
} catch ([1]) {
    echo "Caught an exception.";
}
?>
Drag options to blanks, or click blank then click option'
AError $e
BException $e
CThrowable $e
DException
Attempts:
3 left
💡 Hint
Common Mistakes
Omitting the variable name after the exception class.
Using only the class name without a variable.
4fill in blank
hard

Fill both blanks to create a try-catch block that catches exceptions and prints the message.

PHP
<?php
try {
    [1] new Exception("Something went wrong.");
} catch ([2] $e) {
    echo $e->getMessage();
}
?>
Drag options to blanks, or click blank then click option'
Athrow
Bcatch
CException
DError
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'catch' instead of 'throw' to raise an exception.
Catching with the wrong class.
5fill in blank
hard

Fill all three blanks to create a try-catch-finally block that throws an exception, catches it, and executes finally.

PHP
<?php
try {
    [1] new Exception("Failed operation.");
} catch ([2] $e) {
    echo $e->getMessage();
} finally {
    [3] "Cleanup done.";
}
?>
Drag options to blanks, or click blank then click option'
Athrow
BException
Cecho
Dprint
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'print' instead of 'echo' in finally (both work but only one is correct here).
Missing the variable name in catch block.