将异常传递给自定义异常处理程序方法.Java



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

这里有一个的例子

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

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

e instanceof UnsupportedOperationException

您需要使用instanceof而不是==,因为您试图比较两种不同的类型。

if(e instanceof UnsupportedOperationException)

etc

最新更新