【发布时间】:2020-10-11 02:20:49
【问题描述】:
我已经使用另一个函数中的 Exception 参数创建了一个返回错误消息的助手。(这是一个示例)
void func(int n){
try {
// this will throw ArithmeticException if n is 0
int x = 10 / n;
int y[] = new int[n];
y[x] = 10;
// this will throw ArrayIndexOutOfBoundsException
// if the value of x surpasses
// the highest index of this array
System.out.println("No exception arose");
}
catch (Exception e) {
System.out.println(getErrorType(e));
}
}
String getErrorType(Exception e){
String errorMessage = "";
if (e instanceof ArithmeticException)
errorMessage = "ArithmeticException, Can't divide by 0";
if (e instanceof ArrayIndexOutOfBoundsException)
errorMessage = "ArrayIndexOutOfBoundsException, This index doesn't exist in this array";
else
errorMessage = "error";
return errorMessage;
}
如您所见,我使用 instanceof 来获取 Exception 类型,并且我可以向 String 函数添加更多信息,例如来自错误的消息。我也可以在这个助手中包含许多错误类型。 我的问题是,
- 这在 Java 中好用吗?
- 这样使用有很多不便之处?
- 还有另一种方法可以实现我正在尝试做的事情吗?
- 它如何影响性能?
我已经知道 try catch 块中的好用处是使用特定的异常添加带有特定异常的捕获级别。但我想让它成为通用的。
【问题讨论】:
标签: java spring performance try-catch try-catch-finally