Java如何创建自定义异常类?
您可以为自己的应用程序特定目的定义自己的异常类。通过扩展java.lang.Exception用于检查的异常或未检查的异常的类来创建异常类java.lang.RuntimeException。通过创建自己的Exception类,您可以更精确地确定问题。
package org.nhooo.example.fundamental;
public class CustomExceptionExample {
public static void main(String[] args) {
int x = 1, y = 0;
try {
int z = CustomExceptionExample.divide(x, y);
System.out.println("z = " + z);
} catch (DivideByZeroException e) {
e.printStackTrace();
}
}
public static int divide(int x, int y) throws DivideByZeroException {
try {
return (x / y);
} catch (ArithmeticException e) {
String m = x + " / " + y + ", trying to divide by zero";
throw new DivideByZeroException(m, e);
}
}
}class DivideByZeroException extends Exception {
DivideByZeroException() {
}
DivideByZeroException(String message) {
super(message);
}
DivideByZeroException(String message, Throwable cause) {
super(message, cause);
}
}
热门推荐
10 同事生日祝福语简短独特
11 闺蜜小孩祝福语简短
12 堂姐进新房祝福语简短
13 五一快乐祝福语简短老师
14 中考祝福语妹妹文案简短
15 离职送别文案祝福语简短
16 退休祝福语简短独特老师
17 生完孩子祝福语简短
18 高考成绩高分祝福语简短