java - 将异常传递给自定义异常处理程序方法。爪哇
问题描述
我有一个包含大约 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.");
}
}
解决方案
您将要使用 instanceof 而不是 ==,因为您正在尝试比较两种不同的类型。
if(e instanceof UnsupportedOperationException)
ETC
推荐阅读
- azure-devops - Azure DevOps 专用板和任务板
- c# - 在不丢失原始数据的情况下重定向回上一页
- python - 如何为公制和英制创建列表?
- javascript - 如何在 NextJS 中使用 next-iron-session 和自定义 api 路由中间件?
- python - 如何使用 Python 读取大型 Firestore 集合而不会遇到 503 超时错误
- r - 用 R 理解 qqplots 中的样本量
- mysql - 从前端传递参数后查询不显示结果?
- flutter - 启动应用程序时出现白屏(本地化功能)
- sql - 有没有办法选择性地将数据导入 Oracle SQL Developer
- html - 如何在html中链接图像