Bird
0
0

Consider this PHP code:

hard📝 Application Q15 of 15
PHP - Error and Exception Handling

Consider this PHP code:

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, 2) . "\n";
echo divide(5, 0) . "\n";

What will be the output?

AError Error
B5 0
CDivision by zero Division by zero
D5 Division by zero
Step-by-Step Solution
Solution:
  1. Step 1: Analyze divide(10, 2)

    Since 2 is not zero, division happens: 10 / 2 = 5 is returned.
  2. Step 2: Analyze divide(5, 0)

    Since 0 triggers exception, catch returns the message "Division by zero".
  3. Final Answer:

    5 Division by zero -> Option D
  4. Quick Check:

    Valid division returns number; zero divisor returns error message [OK]
Quick Trick: Exception returns message; normal runs return result [OK]
Common Mistakes:
  • Expecting zero instead of error message
  • Thinking exception stops program without catch
  • Confusing return values inside try-catch

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PHP Quizzes