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".

Long Answer
Views 29

Answer:


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

Related Articles:

This section is dedicated exclusively to Questions & Answers. For an in-depth exploration of Java Programming Language, click the links and dive deeper into this subject.

Join Our telegram group to ask Questions

Click below button to join our groups.