Java中如何抛出异常及自定义异常类型

哈喽,本章和大家一起学习异常抛出和类型自定义!

一、抛出异常

  • throw生成异常对象,一般和throws搭配使用

  • throws声明异常类型

二、自定义

  1. 先继承已知的异常类型,一般是Exception或RunTimeException

  2. 用surper引用父类的有参构造(String message)

例题:抛出“马化腾”异常

public class WrongNameException extends RuntimeException {
    public WrongNameException(String message){
        super(message);
    }
}
public class Student {
    private String name;
    private int age;

    public int getAge() {
        return age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) throws WrongNameException {
        if (name.equals("马化腾")) {
            throw new WrongNameException("姓名马化腾异常");
        }
        this.name = name;
    }

    public static void main(String[] args) {
        Student s = new Student();
        try {
            s.setName("马化腾");
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(s.getName());

输出结果

null
cn.kgc.WrongNameException: 姓名马化腾异常
	at cn.kgc.Student.setName(Student.java:28)
	at cn.kgc.Student.main(Student.java:36)

 

    原文作者:烤桔子
    原文地址: https://blog.csdn.net/m0_61072671/article/details/121214996
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞