
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Handle IllegalArgumentException Inside an If Using Java
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.
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
Advertisements