✏️ Explanatory Question

Write a try/catch block that throws an Exception if the value of variable X is less than zero. The exception should return message: "ERROR: Negative value in X coordinate".

👁 35 Views
📘 Detailed Answer
🔴 Hard
💡

Answer with Explanation


int X = -5; // example value

try {
    if (X < 0) {
        throw new Exception("ERROR: Negative value in X coordinate");
    }
    System.out.println("X is valid: " + X);
} 
catch (Exception e) {
    System.out.println(e.getMessage());
}

Output:


ERROR: Negative value in X coordinate