Java 中 'if' 条件语句内如何自动处理 IllegalArgumentException?
当您向方法或构造函数传递不合适的参数时,会抛出 IllegalArgumentException。这是一个运行时异常,因此无需在编译时处理它。
示例
java.sql.Date 类的 valueOf() 方法接受一个表示 JDBC 转义格式 *yyyy-[m]m-[d]d* 的日期的字符串,并将其转换为 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
但是,如果您以任何其他格式传递日期字符串,则此方法会抛出 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
示例
Thread 类的 setPriority() 方法接受一个表示线程优先级的整数值,并将其设置为当前线程。但是,传递给此方法的值应小于线程的最高优先级,否则此方法会抛出 **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 条件限制/验证参数,并避免异常。
示例
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
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP