Complete the code to catch exceptions.
<?php try { // code that may throw an exception } catch ([1] $e) { echo $e->getMessage(); } ?>
The Exception class is the base class for all exceptions in PHP and is used in catch blocks to handle exceptions.
Complete the code to throw an exception.
<?php
function checkAge($age) {
if ($age < 18) {
throw new [1]("Age must be at least 18.");
}
return true;
}
?>The Exception class is used to create and throw exceptions in PHP.
Fix the error in the catch block to properly catch exceptions.
<?php try { throw new Exception("Error occurred."); } catch ([1]) { echo "Caught an exception."; } ?>
The catch block must specify the exception class and a variable to hold the exception object, like Exception $e.
Fill both blanks to create a try-catch block that catches exceptions and prints the message.
<?php try { [1] new Exception("Something went wrong."); } catch ([2] $e) { echo $e->getMessage(); } ?>
Use throw to raise an exception and Exception in the catch block to handle it.
Fill all three blanks to create a try-catch-finally block that throws an exception, catches it, and executes finally.
<?php try { [1] new Exception("Failed operation."); } catch ([2] $e) { echo $e->getMessage(); } finally { [3] "Cleanup done."; } ?>
Use throw to raise the exception, catch with Exception, and print a message with echo in finally.