如何在 if 中使用 Java 處理 IllegalArgumentException
由於您瞭解方法的合法引數,因此在使用導致 IllegalArgumentException 的方法時,您可以預先使用 if 條件限制/驗證引數,並避免發生異常。
我們可以使用 if 語句限制方法的引數值。例如,如果某個方法接受特定範圍內的值,則可以在執行方法之前使用 if 語句驗證引數的範圍。
示例
以下示例使用 if 語句處理了 setPriority() 方法導致的 IllegalArgumentException。
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