【发布时间】:2020-03-17 05:50:04
【问题描述】:
我有一个包含大约 20 个方法的类,它们都捕获 1 个或多个异常,然后根据该异常响应用户。我不想一遍又一遍地编写它们,而是想创建一个传递异常、处理它并给出适当响应的方法。
这是一个例子
public boolean addFirst(Object data){
try {
//add something
return true;
} catch(Exception e) {
exceptionHandler(e);
return false;
}
}
但是当我尝试将它与“e”进行比较时,它给了我“Exception 无法解析为变量”。
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.");
}
}
【问题讨论】:
-
“它不喜欢我将异常视为变量” 是什么意思?请添加正在发生的编译器错误或警告。
-
嘿,对不起,我不是很准确。刚刚修好了。
标签: java exception methods parameter-passing