如何在Java中的“ if”条件内自动处理IllegalArgumentException?
每当您将不适当的参数传递给方法或构造函数时,都会引发IllegalArgumentException。这是运行时异常,因此在编译时无需处理此异常。
示例
valueOf()java.sql.Date类的方法接受一个以JDBC转义格式yyyy-[m]m-[d]d表示日期的String,并将其转换为java.sql.Date对象。
import java.sql.Date;
import java.util.Scanner;
public class IllegalArgumentExample {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter your date of birth in JDBC escape format (yyyy-mm-dd) ");
String dateString = sc.next();
Date date = Date.valueOf(dateString);
System.out.println("Given date converted int to an object: "+date);
}
}输出结果
Enter your date of birth in JDBC escape format (yyyy-mm-dd) 1989-09-26 Given date converted into an object: 1989-09-26
但是,如果您以其他任何格式传递dateString,则此方法将引发IllegalArgumentException。
import java.sql.Date;
import java.util.Scanner;
public class IllegalArgumentExample {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter your date of birth in JDBC escape format (yyyy-mm-dd) ");
String dateString = sc.next();
Date date = Date.valueOf(dateString);
System.out.println("Given date converted int to an object: "+date);
}
}运行时异常
Enter your date of birth in JDBC escape format (yyyy-mm-dd) 26-07-1989 Exception in thread "main" java.lang.IllegalArgumentException at java.sql.Date.valueOf(Unknown Source) at july_ipoindi.NextElementExample.main(NextElementExample.java:11) In the following Java example the Date constructor (actually deprecated) accepts
示例
setPriority()Thread类的方法接受一个表示线程优先级的整数值,并将其设置为当前线程。但是,传递给此方法的值应小于线程的最大优先级,否则此方法将抛出IllegalArgumentException。
public class IllegalArgumentExample {
public static void main(String args[]) {
Thread thread = new Thread();
System.out.println(thread.MAX_PRIORITY);
thread.setPriority(12);
}
}运行时异常
10Exception in thread "main" java.lang.IllegalArgumentException at java.lang.Thread.setPriority(Unknown Source) at july_ipoindi.NextElementExample.main(NextElementExample.java:6)
在if条件下处理IllegalArgumentException
在使用导致IllegalArgumentException的方法时,由于您知道它们的合法参数,因此可以事先使用if-condition限制/验证参数,并避免出现异常。
示例
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);
}
}
}输出结果
Enter the thread priority value: 15 Priority value should be less than: 10