Home / Questions / 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".
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".

👁 30 Views
📘 Detailed Answer
🕒 Easy to Read
Read the answer carefully and go through the related questions on the right side to improve your understanding of this topic.

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