【大数据】学习笔记
1 Java SE
第8章 异常
8.3 自定义异常
为什么需要自定义异常类:
我们说了Java中不同的异常类,分别表示着某一种具体的异常情况,那么在开发中总是有些异常情况是核心类库中没有定义好的,此时我们需要根据自己业务的异常情况来定义异常类。例如年龄负数问题,考试成绩负数问题等等。
异常类如何定义:
- 自定义一个编译时异常类型:自定义类 并继承
java.lang.Exception
。 - 自定义一个运行时异常类型:自定义类 并继承
java.lang.RuntimeException
。
注意自定义的异常只能通过throw抛出。
演示自定义异常:
package com.dingjiaxiong.define;
/**
* @Projectname: BigDataStudy
* @Classname: NotTriangleException
* @Author: Ding Jiaxiong
* @Date:2023/4/27 15:17
*/
public class NotTriangleException extends Exception {
public NotTriangleException() {
}
public NotTriangleException(String message) {
super(message);
}
}
package com.dingjiaxiong.define;
/**
* @Projectname: BigDataStudy
* @Classname: Triangle
* @Author: Ding Jiaxiong
* @Date:2023/4/27 15:17
*/
public class Triangle {
private double a;
private double b;
private double c;
public Triangle(double a, double b, double c) throws NotTriangleException {
if (a <= 0 || b <= 0 || c <= 0) {
throw new NotTriangleException("三角形的边长必须是正数");
}
if (a + b <= c || b + c <= a || a + c <= b) {
throw new NotTriangleException(a + "," + b + "," + c + "不能构造三角形,三角形任意两边之后必须大于第三边");
}
this.a = a;
this.b = b;
this.c = c;
}
public double getA() {
return a;
}
public void setA(double a) throws NotTriangleException {
if (a <= 0) {
throw new NotTriangleException("三角形的边长必须是正数");
}
if (a + b <= c || b + c <= a || a + c <= b) {
throw new NotTriangleException(a + "," + b + "," + c + "不能构造三角形,三角形任意两边之后必须大于第三边");
}
this.a = a;
}
public double getB() {
return b;
}
public void setB(double b) throws NotTriangleException {
if (b <= 0) {
throw new NotTriangleException("三角形的边长必须是正数");
}
if (a + b <= c || b + c <= a || a + c <= b) {
throw new NotTriangleException(a + "," + b + "," + c + "不能构造三角形,三角形任意两边之后必须大于第三边");
}
this.b = b;
}
public double getC() {
return c;
}
public void setC(double c) throws NotTriangleException {
if (c <= 0) {
throw new NotTriangleException("三角形的边长必须是正数");
}
if (a + b <= c || b + c <= a || a + c <= b) {
throw new NotTriangleException(a + "," + b + "," + c + "不能构造三角形,三角形任意两边之后必须大于第三边");
}
this.c = c;
}
@Override
public String toString() {
return "Triangle{" +
"a=" + a +
", b=" + b +
", c=" + c +
'}';
}
}
测试类
package com.dingjiaxiong.define;
/**
* @Projectname: BigDataStudy
* @Classname: TestTriangle
* @Author: Ding Jiaxiong
* @Date:2023/4/27 15:17
*/
public class TestTriangle {
public static void main(String[] args) {
Triangle t = null;
try {
t = new Triangle(2, 2, 3);
System.out.println("三角形创建成功:");
System.out.println(t);
} catch (NotTriangleException e) {
System.err.println("三角形创建失败");
e.printStackTrace();
}
try {
if (t != null) {
t.setA(1);
}
System.out.println("三角形边长修改成功");
} catch (NotTriangleException e) {
System.out.println("三角形边长修改失败");
e.printStackTrace();
}
}
}
测试结果