Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (6.1k points)
Can anybody clear my doubt as I am new to Java?

1 Answer

0 votes
by (11.7k points)

In Java, when an inappropriate or illegal argument is passed, this exception is thrown in order to let the programmer know that a wrong argument has been passed. 

public class Employee {

   int a;

   public void setAge(int age) {

      if(age < 0 || age > 100)

         throw new IllegalArgumentException(Integer.toString(age));

      else

         a = age;

   }

   public static void main(String[] args) {

      Employee e1 = new Employee();

      e1.setAge(45);

      System.out.println(e1.a);

      Employee e2 = new Employee();

      e2.setAge(101);

      System.out.println(e2.a);

   }

}

Output:

Exception in thread "main" java.lang.IllegalArgumentException: 101

at Employee.setAge(Employee.java:5)

at Employee.main(Employee.java:15)

Browse Categories

...