How to handle IllegalArgumentException inside an if using Java

JavaServer Side ProgrammingProgramming

While you use the methods that causes IllegalArgumentException, since you know the legal arguments of them, you can restrict/validate the arguments using if-condition before-hand and avoid the exception.

We can restrict the argument value of a method using the if statement. For example, if a method accepts values of certain range, you can verify the range of the argument using the if statement before executing the method.

Example

Following example handles the IllegalArgumentException caused by the setPriority() method using the if statement.

Live Demo

import java.util.Scanner;
public class IllegalArgumentExample {
   public static void main(String args[]) {
      Thread thread = new Thread();
      System.out.println("Enter the thread priority value: ");
      Scanner sc = new Scanner(System.in);
      int priority = sc.nextInt();
      if(priority<=Thread.MAX_PRIORITY) {
         thread.setPriority(priority);
      }else{
         System.out.println("Priority value should be less than: "+Thread.MAX_PRIORITY);
      }      
   }      
}

Output

Enter the thread priority value:
15
Priority value should be less than: 10
raja
Published on 08-Feb-2021 11:18:44
Advertisements