Java的异常是比较独特的,它是程序安全稳定的重要措施。本次作业要求自定义异常并使用异常。
(1)自定义一个异常类,注意其继承自系统的异常类,并要求有构造方法;
(2)使用自定义的异常:要求在一个函数中抛出异常,在另一段程序中调用这个函数并捕获异常。
package text;
import java.util.Scanner;
public class MyException {
public static void main(String[] args) {
People xiaozhang=new People();
System.out.print("请输入年龄:");
Scanner input=new Scanner(System.in);
int age=input.nextInt();
input.close();
Check check1 = new Check();
try {
check1.CheckAge(age);
xiaozhang.setAge(age);
} catch (AgeException e) {
// TODO Auto-generated catch block
System.out.println("————————————————————————————————————————————————");
e.printStackTrace();
System.out.println("————————————————————————————————————————————————");
System.out.println(e.getMessage());
System.out.println("————————————————————————————————————————————————");
}
System.out.println("我继续运行");
}
}
class People{
protected String name;
protected String sex;
protected int age;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age=age;
}
}
class SexException extends Exception{
public SexException(String msg) {
super(msg);
}
}
class AgeException extends Exception{
public AgeException(String msg) {
super(msg);
}
}
class Check{
public void CheckSex(String Sex)throws SexException{
if (Sex.equals("boy")||Sex.equals("girl")||Sex.equals("男")||Sex.equals("女")){
System.out.println("性别符合要求");
}
else{throw new SexException("性别不符合要求");}
}
public void CheckAge(int Age) throws AgeException {
if(Age<120&&Age>17) {
System.out.println("年龄符合要求");
}
else {throw new AgeException("年龄不符合要求");}
}
}