关于创建自定义异常

On creating custom exceptions

java 中的异常是如何定义的?我该如何定义自己的异常? 例如,我们有 ArithmeticException 禁止我们除以 0 并且不会破坏程序。

try-catch 使用 if-else 逻辑捕获相同潜在错误的优势是什么?

另外,假设我不是在所有整数的域上操作,而是具体地在加法下形成的域Z2其中1+1=0.

假设我已经预先定义了一组操作逻辑,我是否可以这样做:

try {
    int a = 1;
    int b = 1;
    int c = a/(a+b);
} catch(myError e) {
//
}

其中 myError :

public class myError extends Exception {
    public myError(String e) {
        super(e);
    }
}

但是,try-catch 子句如何知道它应该捕获 myError?是什么让 myError 成为现在的样子? 换句话说:什么定义了,例如,ArithmeticException,以寻找被 0 除以其他东西?

或者我可以 throw new myError("something's wrong") ,但这会破坏定义 "custom" 异常的全部意义,因为我可以抛出任何类似的异常。

例外只是 class 扩展 class Throwable 的那些。通过创建扩展 Throwable 或其子 class 之一的 class 来定义您自己的异常。

您可以使用 throw new myError(); 引发您自己的异常。

ArithmeticException 是除以零时 JVM 抛出的特殊异常。寻找除以零的地方也不例外; / 就是这样工作的。 / 运算符检查分母是否为零,然后抛出异常。

无法向 + 运算符添加检查,以便在两个数字相加的结果为零时抛出任何异常。您必须编写自己的方法来检查和执行此操作。

public int add(int a, int b) {
    int result = a + b;
    if (result == 0) {
        throw new myError();
    }
    return result;
}

// Then use the add() method instead of +
try {
    int a = 1;
    int b = -1;
    int result = add(a, b);
    System.out.println(result);
} catch (myError e) {
    System.out.println("The result was zero!");
}