0
点赞
收藏
分享

微信扫一扫

finally中不要写return语句

TiaNa_na 2022-04-29 阅读 44

如果finally有return语句,永远返回finally中的结果,避免该情况.

正常情况

package cn.itcast.test;

public class TryTest8 {
    public static void main(String[] args) {
        int value = show(0);
        System.out.println("value = " + value);
    }

    public static int show(int x)
    {
        try
        {
            if(x==0){
                throw new Exception("x是零");
            }
            System.out.println("try.....");
            return 1;
        }catch(Exception e)
        {
            e.printStackTrace();
            System.out.println("捕获异常");
            return 2;
        }finally
        {
            System.out.println("必须执行");
            //return 3;
        }
    }
}

在这里插入图片描述

finally中加了return

  • 永远都是返回finally中的结果
package cn.itcast.test;

public class TryTest8 {
    public static void main(String[] args) {
        int value = show(0);
        System.out.println("value = " + value);
    }

    public static int show(int x)
    {
        try
        {
            if(x==0){
                throw new Exception("x是零");
            }
            System.out.println("try.....");
            return 1;
        }catch(Exception e)
        {
            e.printStackTrace();
            System.out.println("捕获异常");
            return 2;
        }finally
        {
            System.out.println("必须执行");
            return 3;
        }
    }
}

在这里插入图片描述

举报

相关推荐

0 条评论