Syn*_*ter 2 java exception-handling try-catch throws
我正在尝试HandleException一种可以处理各种异常的方法。
问题是,我的函数返回一个值。但是,如果我HandleException在 catch 块中使用,Java 会抱怨该函数不返回值,即使我的 HandleException 总是抛出异常。
什么是解决这个问题的好方法?谢谢!
这是一个示例代码。
public class MyException {
static int foo(int num) throws Exception {
try {
return bar(num);
} catch (Exception e) {
handleException();
// throw new Exception("Exception in foo", e);
}
}
static int bar(int num) throws IllegalArgumentException {
if (num < 0) {
throw new IllegalArgumentException("Num less than 0");
}
return num;
}
static void handleException(Exception e) throws Exception {
System.err.println("Handling Exception: " + e);
throw new Exception(e);
}
public static void main(String[] args) throws Exception {
int value = foo(-1);
}
}
Run Code Online (Sandbox Code Playgroud)
在我原来的班级中,我有很多具有这种格式的方法。
try {
...
} catch (Exception1) {
Log exception
throw appropriate exception
} catch (Exception2) {
Log exception
throw appropriate exception
}
Run Code Online (Sandbox Code Playgroud)
我试图想出一种更简洁的方式来编写 catch 块。
这是因为在 handleException 上抛出的异常已经被 foo 方法的 catch 块捕获了。因此 foo 方法不再抛出异常,使得 catch 块不返回任何内容。因此,如果 bar 方法抛出异常,它将转到 catch 块,但由于 catch 块没有返回任何内容,Java 会执行 catch 块之后的行,但是当它到达末尾时,它会抛出一个错误“该方法必须返回一个int 类型的结果”,因为您没有 return 语句。
你应该改变这部分。
public class MyException {
static int foo(int num) throws Exception {
try {
return bar(num);
} catch (Exception e) {
throw handleException(e); // this will throw the exception from the handleException
// throw new Exception("Exception in foo", e);
}
}
static int bar(int num) throws IllegalArgumentException {
if (num < 0) {
throw new IllegalArgumentException("Num less than 0");
}
return num;
}
// This method now returns an exception, instead of throwing an exception
static Exception handleException(Exception e) {
System.err.println("Handling Exception: " + e);
return new Exception(e);
}
public static void main(String[] args) throws Exception {
int value = foo(-1);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8726 次 |
| 最近记录: |