概述

可以继承的父类有Throwable、Exception、RunTimeException,一般继承后两个,如果不要求调用者一定要处理抛出的异常,就继承RuntimeException

自定义异常类构造方法

idea可以自动生成,Alt+Insert快捷键,选择构造方法

代码如下

MyException.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
/**
* @author LeDao
* @company
* @create 2021-07-07 10:43
*/
public class MyException extends RuntimeException{

public MyException() {
}

public MyException(String message) {
super(message);
}

public MyException(String message, Throwable cause) {
super(message, cause);
}

public MyException(Throwable cause) {
super(cause);
}

public MyException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}

People.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
/**
* @author LeDao
* @company
* @create 2021-07-07 10:45
*/
public class People {

private String name;
private String sex;

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getSex() {
return sex;
}

public void setSex(String sex) throws MyException {
if ("男".equals(sex) || "女".equals(sex)) {
this.sex = sex;
} else {
throw new MyException("性别必须是男或女");
}
}
}

Test.java

1
2
3
4
5
6
7
8
9
10
11
12
/**
* @author LeDao
* @company
* @create 2021-06-21 12:38
*/
public class Test {

public static void main(String[] args) {
People people = new People();
people.setSex("11");
}
}

结果

img

PS.

来源:Java自定义异常 - 拭不去の泪痕 - 博客园