【JavaSE】异常(异常体系、异常处理方式、自定义异常)

异常介绍

异常体系

一定要能阐述异常的体系结构!
异常类的祖先类:Throwable
所有的异常都是一个类,如果不清楚可以在API帮助文档查询

运行时异常:编译时没有错误,运行时可能会出错,通常是代码不严谨导致的
编译时异常(不包含语法错误):主要起提醒作用,需要在运行之前给出解决方式

常见的运行时异常:

异常处理方式

异常的默认处理流程

异常处理方式的选择

方式1:try catch捕获异常

方式2:throws抛出异常

throw和throws的区别

Student.java
package com.EveX.domain;

public class Student {
    String name;
    int age;

    public Student() {
    }

    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    /**
     * 获取
     * @return name
     */
    public String getName() {
        return name;
    }

    /**
     * 设置
     * @param name
     */
    public void setName(String name) {
        this.name = name;
    }

    /**
     * 获取
     * @return age
     */
    public int getAge() {
        return age;
    }

    /**
     * 设置
     * @param age
     */
    public void setAge(int age) throws Exception {
        if(age > 120 || age < 0) {
            throw new Exception("输入年龄范围有误,请重新输入");
        }
        this.age = age;
    }

    public String toString() {
        return "Student{name = " + name + ", age = " + age + "}";
    }
}

ExceptionDemo.java
package com.EveX.exception.handle;

import com.EveX.domain.Student;

import java.util.Scanner;

public class ExceptionDemo {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);

        Student stu = new Student();
        System.out.println("请输入姓名:");
        String name = in.nextLine();
        stu.setName(name);
        System.out.println("请输入年龄:");
        int age = 0;

        while (true) {
            try {
                age = Integer.parseInt(in.nextLine());
                stu.setAge(age);
                break;
            } catch (NumberFormatException e) {
                System.out.println("NumberFormatException,请重新输入整数:");
            } catch (Exception e) {
                System.out.println(e.getMessage());
            }
        }


        System.out.println(stu);

    }
}

自定义异常

StudentAgeException.java
package com.EveX.exception;

public class StudentAgeException extends RuntimeException{
    public StudentAgeException() {
    }

    public StudentAgeException(String message) {
        super(message);
    }
}
Student.java
package com.EveX.domain;

import com.EveX.exception.StudentAgeException;

public class Student {
    String name;
    int age;

    public Student() {
    }

    public Student(String name, int age) {
        this.name = name;
        setAge(age);
    }

    /**
     * 获取
     * @return name
     */
    public String getName() {
        return name;
    }

    /**
     * 设置
     * @param name
     */
    public void setName(String name) {
        this.name = name;
    }

    /**
     * 获取
     * @return age
     */
    public int getAge() {
        return age;
    }

    /**
     * 设置
     * @param age
     */
    public void setAge(int age) throws StudentAgeException {
        if(age > 120 || age < 0) {
            throw new StudentAgeException("输入年龄范围有误,请重新输入");
        }
        this.age = age;
    }

    public String toString() {
        return "Student{name = " + name + ", age = " + age + "}";
    }
}

TryCatchDemo.java
package com.EveX.exception.handle;

import com.EveX.domain.Student;
import com.EveX.exception.StudentAgeException;

import java.util.Scanner;

public class TryCatchDemo {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);

        Student stu = new Student();
        System.out.println("请输入姓名:");
        String name = in.nextLine();
        stu.setName(name);
        System.out.println("请输入年龄:");
        int age = 0;

        while (true) {
            try {
                age = Integer.parseInt(in.nextLine());
                stu.setAge(age);
                break;
            } catch (NumberFormatException e) {
                System.out.println("NumberFormatException,请重新输入整数:");
            } catch (StudentAgeException e) {
                System.out.println(e.getMessage());
            }
        }

        System.out.println(stu);

    }
}

异常的细节

异常案例练习

需求

代码

ExceptionTest.java
package com.EveX.exception.handle;

import com.EveX.domain.Student;
import com.EveX.exception.StudentAgeException;
import com.EveX.exception.StudentScoreException;

import java.util.Scanner;

public class ExceptionTest {
    public static final int MATH = 1;
    public static final int CHINESE = 2;
    public static final int ENGLISH = 3;
    public static Scanner in = new Scanner(System.in);
    public static void main(String[] args) {

        Student[] stu = new Student[3];

        for(int i = 0; i < 3; ++ i ) {
            stu[i] = new Student();
            System.out.println("请输入第" + (i + 1) + "个学生的信息!");

            System.out.print("姓名:");
            String name = in.nextLine();
            stu[i].setName(name);

            int age = 0;
            while (true) {
                try {
                    System.out.print("年龄:");
                    age = Integer.parseInt(in.nextLine());
                    stu[i].setAge(age);
                    break;
                } catch (NumberFormatException e) {
                    System.out.println("请确保输入的年龄是整数!");
                } catch (StudentAgeException e) {
                    System.out.println(e.getMessage());
                }
            }

            setScore(stu[i], MATH);

            setScore(stu[i], CHINESE);

            setScore(stu[i], ENGLISH);
        }

        for(int i = 0; i < 3; ++ i ) {
            System.out.println(stu[i]);
        }
    }

    private static void setScore(Student stu, int subject) {
        String msg = "";
        switch (subject) {
            case MATH -> msg = "数学成绩:";
            case CHINESE -> msg = "语文成绩:";
            case ENGLISH -> msg = "英语成绩:";
        }
        double score = 0;
        while (true) {
            try {
                System.out.print(msg);
                score = Double.parseDouble(in.nextLine());
                switch (subject) {
                    case MATH -> stu.setMathScore(score);
                    case CHINESE -> stu.setChineseScore(score);
                    case ENGLISH -> stu.setEnglishScore(score);
                }
                break;
            } catch (NumberFormatException e) {
                System.out.println("请确保输入的成绩是小数!");
            } catch (StudentScoreException e) {
                System.out.println(e.getMessage());
            }
        }
    }

}
Student.java
package com.EveX.domain;

import com.EveX.exception.StudentAgeException;
import com.EveX.exception.StudentScoreException;

public class Student {
    String name;
    int age;
    double mathScore;
    double chineseScore;
    double englishScore;


    public Student() {
    }

    public Student(String name, int age, double mathScore, double chineseScore, double englishScore) {
        this.name = name;
        setAge(age);
        setMathScore(mathScore);
        setChineseScore(chineseScore);
        setEnglishScore(englishScore);
    }

    /**
     * 获取
     * @return name
     */
    public String getName() {
        return name;
    }

    /**
     * 设置
     * @param name
     */
    public void setName(String name) {
        this.name = name;
    }

    /**
     * 获取
     * @return age
     */
    public int getAge() {
        return age;
    }

    /**
     * 设置
     * @param age
     */
    public void setAge(int age) {
        if(age >= 0 && age <= 120) {
            this.age = age;
        } else {
            throw new StudentAgeException("年龄输入有误,请确保年龄在0~120之间!");
        }

    }

    /**
     * 获取
     * @return mathScore
     */
    public double getMathScore() {
        return mathScore;
    }

    /**
     * 设置
     * @param mathScore
     */
    public void setMathScore(double mathScore) {
        judge(mathScore);
        this.mathScore = mathScore;
    }

    private static void judge(double score) {
        if(score < 0 || score > 100) {
            throw new StudentScoreException("请确保输入的成绩在0~100分之间!");
        }
    }

    /**
     * 获取
     * @return chineseScore
     */
    public double getChineseScore() {
        return chineseScore;
    }

    /**
     * 设置
     * @param chineseScore
     */
    public void setChineseScore(double chineseScore) {
        judge(chineseScore);
        this.chineseScore = chineseScore;
    }

    /**
     * 获取
     * @return englishScore
     */
    public double getEnglishScore() {
        return englishScore;
    }

    /**
     * 设置
     * @param englishScore
     */
    public void setEnglishScore(double englishScore) {
        judge(englishScore);
        this.englishScore = englishScore;
    }

    public String toString() {
        return "Student{name = " + name + ", age = " + age + ", mathScore = " + mathScore + ", chineseScore = " + chineseScore + ", englishScore = " + englishScore + "}";
    }
}
StudentAgeException.java
package com.EveX.exception;

public class StudentAgeException extends RuntimeException{
    public StudentAgeException() {
    }

    public StudentAgeException(String message) {
        super(message);
    }
}
StudentScoreException.java
package com.EveX.exception;

public class StudentScoreException extends RuntimeException{
    public StudentScoreException() {
    }

    public StudentScoreException(String message) {
        super(message);
    }
}
posted @ 2023-12-02 22:23  沙汀鱼  阅读(21)  评论(0编辑  收藏  举报