public void setAge(int age) { if(age < 0) { throw new IllegalArgumentException("Age cannot be negative."); } this.age = age; }
public void calculateArea(int length, int width) { if(length <= 0 || width <= 0) { throw new IllegalArgumentException("Length and width should be positive."); } int area = length * width; System.out.println("Area is: " + area); }In this example, the calculateArea() method calculates the area of a rectangle using the length and width provided as arguments. If either of the arguments is negative or zero, it throws an IllegalArgumentException with the message "Length and width should be positive." The IllegalArgumentException class is part of the java.lang package in Java.