gpt4 book ai didi

java - 将异常传递给自定义异常处理程序方法。 java

转载 作者:行者123 更新时间:2023-12-02 01:00:26 25 4
gpt4 key购买 nike

我有一个包含大约 20 个方法的类,这些方法都捕获 1 个或多个异常,然后根据该异常响应用户。我不想一遍又一遍地编写它们,而是想创建一个传递异常、处理它并给出适当响应的单一方法。

这是一个例子

public boolean addFirst(Object data){

try {
//add something
return true;
} catch(Exception e) {
exceptionHandler(e);
return false;
}
}

但是当我尝试将它与“e”进行比较时,它给出了“异常无法解析为变量”。

private void exceptionHandler(Exception e) {
if(e == UnsupportedOperationException) {
System.out.println("Operation is not supported.");
} else if (e == ClassCastException) {
System.out.println("Class of the specified element prevents it from being added to this list.");
} else if (e == NullPointerException) {
System.out.println("You cannot enter nothing.");
} else if (e == IndexOutOfBoundsException) {
System.out.println("Your specified index is larger than the size of the LinkedList. Please choose a lower value.");
} else if(e == Exception) {
System.out.println("You messed up so hard that I don't even know what you did wrong.");
}
}

最佳答案

例如UnsupportedOperationException 不是声明的变量,这就是编译器提示的内容。

当执行e == UnsupportedOperationException时,您正在检查e的引用是否等于UnsupportedOperationException的引用,但UnsupportedOperationException code> 从未声明过。

要检查对象的类型,您必须使用 instanceof 关键字和要检查的 class

e instanceof UnsupportedOperationException

关于java - 将异常传递给自定义异常处理程序方法。 java ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60716864/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com