✏️ Explanatory Question

Which of the following Java programs will result in a runtime error, and why?

public class RuntimeErrorExample {
    public static void main(String[] args) {
        int a = 10;
        int b = 0;
        int result = a / b; 
        System.out.println("Result: " + result);
    }
}

👁 125 Views
📘 Detailed Answer
🟢 Easy
No previous question
No next question
💡

Answer with Explanation

This program will compile successfully but will crash at runtime due to division by zero (10 / 0), causing an ArithmeticException.

Fixed Code (Using Exception Handling):


public class RuntimeErrorExample {
    public static void main(String[] args) {
        int a = 10;
        int b = 0;
        try {
            int result = a / b; // Risky operation
            System.out.println("Result: " + result);
        } catch (ArithmeticException e) {
            System.out.println("Error: Division by zero is not allowed.");
        }
    }
}

This ensures that the program handles the error gracefully instead of crashing. 🚀

No previous question
No next question