0
0
PHPprogramming~10 mins

Finally block behavior 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 ensure the finally block always executes.

PHP
<?php
try {
    echo "Try block executed.\n";
} [1] {
    echo "Catch block executed.\n";
} finally {
    echo "Finally block executed.\n";
}
?>
Drag options to blanks, or click blank then click option'
Acatch (Error $e)
Bcatch
Ccatch (Exception $e)
Dcatch (Throwable $e)
Attempts:
3 left
💡 Hint
Common Mistakes
Omitting the catch block causes syntax errors.
Using an incorrect catch syntax.
2fill in blank
medium

Complete the code to throw an exception inside the try block.

PHP
<?php
try {
    throw new [1]("Error occurred.");
} catch (Exception $e) {
    echo $e->getMessage();
} finally {
    echo "\nFinally block runs.";
}
?>
Drag options to blanks, or click blank then click option'
AException
BError
CThrowable
DRuntimeException
Attempts:
3 left
💡 Hint
Common Mistakes
Using a class that is not an Exception or subclass.
Forgetting the 'new' keyword.
3fill in blank
hard

Fix the error in the catch block syntax.

PHP
<?php
try {
    echo "Inside try.\n";
} catch [1] {
    echo "Caught exception.\n";
} finally {
    echo "Finally block executed.\n";
}
?>
Drag options to blanks, or click blank then click option'
A(Error $e)
B(Throwable $e)
C(Exception)
D(Exception $e)
Attempts:
3 left
💡 Hint
Common Mistakes
Omitting the variable name in catch parentheses.
Using incorrect parentheses syntax.
4fill in blank
hard

Fill both blanks to create a finally block that always runs after try and catch.

PHP
<?php
try {
    echo "Trying...\n";
} catch (Exception $e) {
    echo "Exception caught.\n";
} [1] {
    echo "[2] block executed.\n";
}
?>
Drag options to blanks, or click blank then click option'
Afinally
Ccatch
Dtry
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'catch' instead of 'finally' for the last block.
Omitting the finally block.
5fill in blank
hard

Fill all three blanks to handle an exception and ensure the finally block runs.

PHP
<?php
try {
    throw new [1]("Error!");
} catch ([2] $e) {
    echo $e->getMessage();
} [3] {
    echo "\nFinally block executed.";
}
?>
Drag options to blanks, or click blank then click option'
AException
Cfinally
Dcatch
Attempts:
3 left
💡 Hint
Common Mistakes
Mismatching exception types in throw and catch.
Using 'catch' instead of 'finally' for the last block.