0
0
PHPprogramming~20 mins

Throwing exceptions in PHP - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Exception Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
What is the output of this PHP code with exception?
Look at the code below. What will it output when run?
PHP
<?php
function test() {
    try {
        throw new Exception("Error happened");
    } catch (Exception $e) {
        return $e->getMessage();
    }
}
echo test();
?>
AException
BError happened
CFatal error
DNo output
Attempts:
2 left
💡 Hint
The catch block returns the exception message.
Predict Output
intermediate
2:00remaining
What error does this PHP code raise?
What error will this code produce when run?
PHP
<?php
function example() {
    throw new Exception("Oops");
}
example();
echo "Done";
?>
AParse error
BDone
CNo output
DUncaught Exception: Oops
Attempts:
2 left
💡 Hint
There is no try-catch block to handle the exception.
🔧 Debug
advanced
2:00remaining
Why does this PHP code cause a fatal error?
This code tries to throw an exception but causes a fatal error. Why?
PHP
<?php
try {
    throw new Exception("Fail");
} catch (Error $e) {
    echo "Caught error";
}
?>
ABecause Exception class is undefined
BBecause catch block is empty
CBecause Exception is not caught by catch(Error $e)
DBecause throw syntax is wrong
Attempts:
2 left
💡 Hint
Exception and Error are different classes in PHP.
📝 Syntax
advanced
2:00remaining
Which option correctly throws and catches an exception?
Choose the code snippet that correctly throws and catches an exception in PHP.
A<?php try { throw new Exception("Error"); } catch (Exception $e) { echo $e->getMessage(); } ?>
B<?php try { throw new Exception("Error") } catch Exception $e { echo $e->getMessage(); } ?>
C<?php try { throw new Exception("Error"); } catch (Exception $e) echo $e->getMessage(); ?>
D<?php try { throw new Exception("Error"); } catch (Exception $e) { echo $e->message; } ?>
Attempts:
2 left
💡 Hint
Check for correct syntax: semicolons, parentheses, and method calls.
🚀 Application
expert
2:00remaining
How many items are in the array after exception handling?
What is the number of elements in the array $results after running this code?
PHP
<?php
$results = [];
try {
    $results[] = 1;
    throw new Exception("Stop");
    $results[] = 2;
} catch (Exception $e) {
    $results[] = 3;
}
$results[] = 4;
print_r($results);
?>
A3
B5
C2
D4
Attempts:
2 left
💡 Hint
Remember that code after throw inside try is skipped.