Mic*_*ael 1 java try-catch-finally
我知道创建一个没有finally块的try-catch段是有效的.因此,在使用此代码进行黑客攻击时,我无法弄清楚java逻辑(例如规则,理论)迫使我在这段代码中包含finally块 - 以及为什么finally块必须在其中包含return语句.换句话说,如果我完全删除finally块我收到一个错误,如果我用finally其他东西替换finally块中的return语句(例如System.out.printl(''foo")),我仍然收到一个错误我坚持要包含一个return语句.再次,这里编写的代码编译并运行正常.我只是想了解try-catch-finally构造背后的一些理论(ps我明白它的全部是关于"异常处理"......但我的问题更多的是关于代码流和返回语句).
class foo {
int getInt() {
try {
String[] students = {"student1", "student2"};
System.out.println(students[4]);
}
catch (Exception e) {
return 10;
}
finally {
return 20;
}
}
public static void main(String args[]) {
foo classSize = new foo();
System.out.println(classSize.getInt());
}
}
Run Code Online (Sandbox Code Playgroud)
考虑没有的执行路径 finally
int getInt() {
try {
String[] students = {"student1", "student2"};
System.out.println(students[4]);
// no return
}
catch (Exception e) {
return 10; // if an exception occurs
}
// no return
}
Run Code Online (Sandbox Code Playgroud)
那么如果没有抛出异常会发生什么?您将没有返回值.
你可以提供一个finally并在那里放一个回报,或者你可以在try-catch区块之外放一个回报.
需要注意的是,finally在你的try-catch-finally块有return将取代该语句catch的return语句因为finally如果相关始终执行块try[-catch]被执行.您可能想要使用以下内容
int getInt() {
try {
String[] students = {"student1", "student2"};
System.out.println(students[4]);
// the return could be here as well
}
catch (Exception e) {
return 10; // in case of failure
}
return 20; // in case of success
}
Run Code Online (Sandbox Code Playgroud)
所有执行路径必须最终返回一个值(或抛出异常).
| 归档时间: |
|
| 查看次数: |
258 次 |
| 最近记录: |