CoreJava/exp9/ExceptionExample4.java

39 lines
1.2 KiB
Java
Raw Normal View History

2024-05-09 09:10:51 +08:00
package exp9;
class ArgumentOutOfBoundsException extends Exception // 自定义一种异常
{
ArgumentOutOfBoundsException() {
System.out.println("输入错误!欲判断的数不能为负数!");
}
}
public class ExceptionExample4 {
public static boolean prime(int m) throws ArgumentOutOfBoundsException {
if (m < 0) {
ArgumentOutOfBoundsException ae = new ArgumentOutOfBoundsException();
throw ae;
} else {
boolean isPrime = true;
for (int i = 2; i < m; i++)
if (m % i == 0) {
isPrime = false;
break;
}
return isPrime;
}
}
public static void main(String args[]) {
if (args.length != 1) {
System.out.println("输入格式错误请按照此格式输入java Usedefine Exception m");
System.exit(0);
}
int m = Integer.parseInt(args[0]); // 读入这个整数
try {
boolean result = prime(m); // 调用方法判断是否为素数
System.out.println("对您输入的整数" + m + "是否为素数的判断结果为:" + result);
} catch (ArgumentOutOfBoundsException e) {
System.out.println("异常名称:" + e.toString());
}
}
}