<class><自定义异常名><extends><Exception>在编码规范上,一般将自定义异常类的类名命名为 XXXException,其中 XXX 用来代表该异常的作用。
class IntegerRangeException extends Exception {
public IntegerRangeException() {
super();
}
public IntegerRangeException(String s) {
super(s);
}
}
public class MyException extends Exception {
public MyException() {
super();
}
public MyException(String str) {
super(str);
}
}
import java.util.InputMismatchException;
import java.util.Scanner;
public class Test07 {
public static void main(String[] args) {
int age;
Scanner input = new Scanner(System.in);
System.out.println("请输入您的年龄:");
try {
age = input.nextInt(); // 获取年龄
if(age < 0) {
throw new MyException("您输入的年龄为负数!输入有误!");
} else if(age > 100) {
throw new MyException("您输入的年龄大于100!输入有误!");
} else {
System.out.println("您的年龄为:"+age);
}
} catch(InputMismatchException e1) {
System.out.println("输入的年龄不是数字!");
} catch(MyException e2) {
System.out.println(e2.getMessage());
}
}
}
3)运行该程序,当用户输入的年龄为负数时,则拋出 MyException 自定义异常,执行第二个 catch 语句块中的代码,打印出异常信息。程序的运行结果如下所示。
请输入您的年龄: -2 您输入的年龄为负数!输入有误!
请输入您的年龄: 110 您输入的年龄大于100!输入有误!
版权说明:Copyright © 广州松河信息科技有限公司 2005-2025 版权所有 粤ICP备16019765号
广州松河信息科技有限公司 版权所有