finally块中不允许使用return,continue或break的原因
2005-10-10 15:44
549 查看
finally块中不允许使用return,continue或break的原因
一个try块可以不执行finally子句就能够退出的唯一方法是通过调用System.exit()方法来实现的。
如果控制因为一个return,continue或break语句离开这个try块,那么finally快会在控制转移到它的新的目标代码之前执行.
也就是说如果在finally块中使用return,continue或break,则会把抛出的异常吃掉。
package test;
public class TryTest {
public static void main(String[] args) {
try {
System.out.println(TryTest.test());// 返回结果为true其没有任何异常
} catch (Exception e) {
System.out.println("Exception from main");
e.printStackTrace();
}
}
public static boolean test() throws Exception {
try {
throw new Exception("Something error");// 1.抛出异常
} catch (Exception e) {// 2.捕获的异常匹配(声明类或其父类),进入控制块
System.out.println("Exception from e");// 3.打印
return false;// 4. return前控制转移到finally块,执行完后再返回
} finally {
return true; // 5. 控制转移,直接返回,吃掉了异常
}
}
}
一个try块可以不执行finally子句就能够退出的唯一方法是通过调用System.exit()方法来实现的。
如果控制因为一个return,continue或break语句离开这个try块,那么finally快会在控制转移到它的新的目标代码之前执行.
也就是说如果在finally块中使用return,continue或break,则会把抛出的异常吃掉。
package test;
public class TryTest {
public static void main(String[] args) {
try {
System.out.println(TryTest.test());// 返回结果为true其没有任何异常
} catch (Exception e) {
System.out.println("Exception from main");
e.printStackTrace();
}
}
public static boolean test() throws Exception {
try {
throw new Exception("Something error");// 1.抛出异常
} catch (Exception e) {// 2.捕获的异常匹配(声明类或其父类),进入控制块
System.out.println("Exception from e");// 3.打印
return false;// 4. return前控制转移到finally块,执行完后再返回
} finally {
return true; // 5. 控制转移,直接返回,吃掉了异常
}
}
}
相关文章推荐
- finally块中不允许使用return,continue或break的原因
- try..catch..finally块中的跳转语句(return,break,continue)使用注意事项
- Java中break、continue、return语句的使用区别对比
- 在Java8的foreach()中使用return/break/continue
- break continue return的区别与使用
- 玩转break,return ,continue的使用和关系
- break,continue,return使用场景, 以及标号的使用
- if,continue,break,while,do-while, switch,return,foreach,for等条件语句的使用
- break continue 和return的使用和区别
- PHP中跳出多重循环使用break,continue,goto,return,exit的用法和区别
- 跳转语句的使用(break,continue,goto,return)
- 在Java8的foreach()中使用return/break/continue
- js---javaScript(循环语句的使用实例)for while do....while(转移语句): break, continue , return
- 循环中使用break和continue,return语句之间的区别
- 代码规范之 break,continue,return 关键字的使用
- java continue,break,return 的使用
- JAVA for语句中的break、continue、return使用简介
- Java中break、continue、return在for循环中的使用
- java循环结构中break、continue、return的区别及使用情景
- SQL server中如何使用return,break和continue