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.


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(;
      int priority = sc.nextInt();
      if(priority<=Thread.MAX_PRIORITY) {
         System.out.println("Priority value should be less than: "+Thread.MAX_PRIORITY);


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