java中try-catch-finally返回值问题
来源:互联网 发布:卡尔曼滤波算法流程图 编辑:程序博客网 时间:2024/04/26 05:44
1 使用规则
如果finally块中有return语句,则try或catch中的return语句被忽略。
finally块中应该避免使用return语句,因为finally块中如果使用return语句,会显示的消化掉try、catch块中的异常信息,屏蔽了错误的发生。
如果仅try/catch语句有return语句,则返回try/catch中变量此时对应的值,此后对变量做任何的修改,都不影响try中return的返回值。
尽量在try/catch中使用return语句,通过finally块中达到对try或者catch返回值修改是不可行的。
如果finally块中抛出异常,则整个try、catch、finally块中抛出异常。
finally块中避免再次抛出异常,否则整个包含try语句块的方法回抛出异常,并且会消化掉try、catch块中的异常。
2 代码示例
public class Demo1 { public static void main(String[] args) { System.out.println(fun1());// try System.out.println(fun2());// catch System.out.println(fun3());// finally System.out.println(fun4());// finally } // 仅try有return语句,返回try中元素值 public static String fun1() { String str = null; try { str = "try"; return str; } catch (Exception e){ str = "catch"; return str; } finally { str = "finally"; } } // 仅catch有return语句,返回catch中元素值 public static String fun2() { String str = null; try { str = "try"; throw new Exception(); } catch (Exception e){ str = "catch"; return str; } finally { str = "finally"; } } // finally中有return,try/catch中的return被忽略 @SuppressWarnings("finally") public static String fun3() { String str = null; try { str = "try"; return str; } catch (Exception e) { str = "catch"; return str; } finally { str = "finally"; return str; } } @SuppressWarnings("finally") public static String fun4() { String str = null; try { str = "try"; throw new Exception(); } catch (Exception e) { str = "catch"; return str; } finally { str = "finally"; return str; } }}
0 0
- java中try-catch-finally返回值问题
- try-catch-finally-return返回值问题
- try catch finally 返回值问题
- try-catch-finally返回值
- java中try、catch、finally返回语句执行顺序
- Java 中 try...catch...finally
- java中try-catch-finally
- Java中Try/catch/finally
- try,catch,finally执行及返回值的问题
- try-catch-finally执行与返回值问题
- try--catch--finally中return返回值执行的顺序
- 关于JAVA的try catch finally的return返回值问题
- 关于JAVA的try catch finally的return返回值问题
- 关于JAVA的try catch finally的return返回值问题
- 【Java】try、catch、finally的执行顺序与返回值问题
- java中关于try、catch、finally中一些问题
- try{}catch{}finally{} 语句块中返回值顺序,Java 值传递引用传递的区别
- java中try{}catch{}和finally{}的执行顺序问题
- 建立一个类PrimeNUM,求指定数据范围内的所有素数(质数)。具体要求如下:
- elasticsearch java api使用,es java封装
- git强制覆盖本地
- 山东省第七届ACM大学生程序设计竞赛 C:Proxy
- 23
- java中try-catch-finally返回值问题
- 深入理解Java:注解(Annotation)自定义注解入门
- 建立一个类SUM,求二维数组外围各元素的和,并且输出数组各元素及所求之和。具体要求如下:
- JAVA 进制转换
- 单链表的初始化、插入、删除、查找
- 数字旋转方阵 分治法
- 历届试题 打印十字图 (蓝桥杯)
- UVA
- jQuery的应用