0
0
PHPprogramming~20 mins

Try-catch execution flow in PHP - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Try-Catch Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of try-catch with exception thrown
What is the output of this PHP code?
PHP
<?php
try {
    echo "Start\n";
    throw new Exception("Error happened");
    echo "End\n";
} catch (Exception $e) {
    echo "Caught: " . $e->getMessage() . "\n";
}
?>
A
Caught: Error happened
Start
B
Start
End
Caught: Error happened
C
Start
End
D
Start
Caught: Error happened
Attempts:
2 left
💡 Hint
Remember that code after throw inside try block is not executed.
Predict Output
intermediate
2:00remaining
Output when no exception is thrown
What will this PHP code output?
PHP
<?php
try {
    echo "Before\n";
    // no exception thrown
    echo "After\n";
} catch (Exception $e) {
    echo "Caught\n";
}
?>
A
Before
After
B
Before
Caught
C
Caught
After
D
After
Attempts:
2 left
💡 Hint
If no exception is thrown, catch block is skipped.
Predict Output
advanced
2:00remaining
Output with finally block execution
What is the output of this PHP code?
PHP
<?php
try {
    echo "Try block\n";
    throw new Exception("Oops");
} catch (Exception $e) {
    echo "Catch block\n";
} finally {
    echo "Finally block\n";
}
?>
A
Try block
Catch block
B
Try block
Finally block
Catch block
C
Try block
Catch block
Finally block
D
Catch block
Finally block
Attempts:
2 left
💡 Hint
Finally block always runs after try and catch.
Predict Output
advanced
2:00remaining
Output when RuntimeException is thrown
What is the output of this PHP code?
PHP
<?php
try {
    echo "Start\n";
    throw new RuntimeException("Runtime error");
} catch (Exception $e) {
    echo "Caught Exception\n";
}
?>
A
Start
Caught Exception
B
Start
Fatal error: Uncaught RuntimeException
C
Caught Exception
D
Start
Attempts:
2 left
💡 Hint
RuntimeException extends Exception, so catch(Exception $e) catches it.
Predict Output
expert
3:00remaining
Output with nested try-catch and rethrow
What is the output of this PHP code?
PHP
<?php
try {
    try {
        echo "Inner try\n";
        throw new Exception("Inner error");
    } catch (Exception $e) {
        echo "Inner catch\n";
        throw $e;
    } finally {
        echo "Inner finally\n";
    }
} catch (Exception $e) {
    echo "Outer catch\n";
} finally {
    echo "Outer finally\n";
}
?>
A
Inner try
Inner catch
Outer catch
Inner finally
Outer finally
B
Inner try
Inner catch
Inner finally
Outer catch
Outer finally
C
Inner try
Inner finally
Inner catch
Outer catch
Outer finally
D
Inner try
Inner catch
Inner finally
Outer finally
Attempts:
2 left
💡 Hint
Remember finally blocks run before control leaves the try or catch blocks.