赞
踩
非法参数异常(IllegalArgumentException)的抛出是为了表明一个方法被传递了一个非法参数。该异常扩展了 RuntimeException 类,因此属于在 Java 虚拟机(JVM)运行期间可能抛出的异常。它是一种未检查异常,因此不需要在方法或构造函数的 throws 子句中声明。
public class Student { int m; public void setMarks(int marks) { if(marks < 0 || marks > 100) throw new IllegalArgumentException(Integer.toString(marks)); else m = marks; } public static void main(String[] args) { Student s1 = new Student(); s1.setMarks(45); System.out.println(s1.m); Student s2 = new Student(); s2.setMarks(101); System.out.println(s2.m); } }
45
Exception in thread "main" java.lang.IllegalArgumentException: 101
at Student.setMarks(Student.java:5)
at Student.main(Student.java:14)
import java.util.Scanner; public class Student { public static void main(String[] args) { String cont = "y"; run(cont); } static void run(String cont) { Scanner scan = new Scanner(System.in); while( cont.equalsIgnoreCase("y")) { try { System.out.println("Enter an integer: "); int marks = scan.nextInt(); if (marks < 0 || marks > 100) throw new IllegalArgumentException("value must be non-negative and below 100"); System.out.println( marks); } catch(IllegalArgumentException i) { System.out.println("out of range encouneterd. Want to continue"); cont = scan.next(); if(cont.equalsIgnoreCase("Y")) run(cont); } } } }
Enter an integer:
1
1
Enter an integer:
100
100
Enter an integer:
150
out of range encouneterd. Want to continue
y
Enter an integer:
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。