Look at this PHP code that tries to divide two numbers. What will it print?
<?php function divide($a, $b) { try { if ($b == 0) { throw new Exception("Division by zero."); } return $a / $b; } catch (Exception $e) { return $e->getMessage(); } } echo divide(10, 0);
Think about what happens when the divisor is zero and how the exception is handled.
The code throws an exception when dividing by zero. The catch block catches it and returns the error message, so the output is the string "Division by zero."
What will this PHP code output?
<?php function divide($a, $b) { return $a / $b; } echo divide(10, 0);
What happens when you divide by zero in PHP without catching errors?
Without error handling, dividing by zero causes a fatal error and the script stops running.
There is a mistake in this PHP code that tries to handle errors. What is it?
<?php function readFileContent($filename) { try { $content = file_get_contents($filename); if (!$content) { throw new Exception("File not found or empty."); } return $content; } catch (Exception $e) { return $e->getMessage(); } } echo readFileContent("missing.txt");
Think about what happens if the file content is the string '0'.
The condition if (!$content) treats '0' as false, so it wrongly throws an exception even if the file exists and contains '0'.
Choose the best reason why error handling is important in PHP applications.
Think about what happens when something unexpected occurs in your program.
Error handling helps the program continue running or fail gracefully instead of crashing unexpectedly.
Analyze this PHP code with nested try-catch blocks. What will it output?
<?php function test() { try { try { throw new Exception("Inner error"); } catch (Exception $e) { echo "Caught: " . $e->getMessage() . "\n"; throw new Exception("Outer error"); } } catch (Exception $e) { echo "Caught again: " . $e->getMessage() . "\n"; } } test();
Look carefully at how exceptions are re-thrown and caught in nested blocks.
The inner try throws "Inner error" which is caught and printed. Then it throws "Outer error" which is caught by the outer catch and printed.