Complete the code to catch an exception in PHP.
<?php try { // Some code that may throw an exception } catch (Exception [1]) { echo 'Error caught!'; } ?>
In PHP, the catch block requires a variable to hold the exception object, commonly $e.
Complete the code to throw an exception when a condition is met.
<?php if ($age < 18) { [1] new Exception('Age must be 18 or older'); } ?>
In PHP, to trigger an exception, you use the throw keyword.
Fix the error in the code to properly handle exceptions.
<?php try { $file = fopen('data.txt', 'r'); if (!$file) { [1] new Exception('File not found'); } } catch (Exception $e) { echo $e->getMessage(); } ?>
The code must use throw to raise an exception inside the try block.
Fill both blanks to create a custom exception class and throw it.
<?php class [1] extends Exception {} try { [2] new [1]('Custom error occurred'); } catch ([1] $e) { echo $e->getMessage(); } ?>
You define a custom exception class by extending Exception. Then you throw an instance of it.
Fill all three blanks to handle multiple exceptions properly.
<?php try { // Some code } catch ([1] $e) { echo 'First error: ' . $e->getMessage(); } catch ([2] $e) { echo 'Second error: ' . $e->getMessage(); } catch ([3] $e) { echo 'General error: ' . $e->getMessage(); } ?>
Use specific exception classes first, then the general Exception class last to catch all other exceptions.
