Java - finally與return

try-return-catch-finally

finally中執(zhí)行返回值是非常不好的做法. 在一些語言中被直接禁止. 因為有很多副作用.

finally中直接使用return返回值

public static int finallyReturn(){
        try{
            System.out.println("about to return 1");
            return 1;
        } finally {
            System.out.println("about to return 2");
            return 2;
        }
    }

    public static int finallyReturnWithException(){
        int[] ints = new int[0];
        try {
            int n = ints[0];
            return n;
        } finally {
            return 2;
        }
    }

    // 異常完全被finally的return給吞了
    public static int finallyReturnWithException2(){
        try {
            System.out.println("about to throw an exception");
            throw new RuntimeException("doomed");
        } finally {
            return 2;
        }


    }
    
    public static void finallyReturnWithException3(){
        try{
            throw new RuntimeException("something is wrong");
        } finally {
            return;
        }
    }
    
    public static void main(String[] args) {

        int result = finallyReturn();
        System.out.println(result);

        result = finallyReturnWithException();
        System.out.println(result);

        try {
            result = finallyReturnWithException2();
        } catch (Exception e){
            // sadly, this won't happen.
            System.out.println("caught the exception");
        }
        System.out.println(result);
        
        try {
            finallyReturnWithException3();
        } catch (Exception e){
            System.out.println("caught the exception");
        }
        
    }
    

輸出:

about to return 1
about to return 2
2
2
about to throw an exception
2

可見finallyreturn的值覆蓋了其他流程中的return值. 更可怕的是finally中使用return, 將本來應(yīng)該拋出的異常也吞了. 所以不應(yīng)該在finally中使用return.

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 1. Java基礎(chǔ)部分 基礎(chǔ)部分的順序:基本語法,類相關(guān)的語法,內(nèi)部類的語法,繼承相關(guān)的語法,異常的語法,線程的語...
    子非魚_t_閱讀 34,835評論 18 399
  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,695評論 19 139
  • 一、基本數(shù)據(jù)類型 注釋 單行注釋:// 區(qū)域注釋:/* */ 文檔注釋:/** */ 數(shù)值 對于byte類型而言...
    龍貓小爺閱讀 4,475評論 0 16
  • 先上源碼: 自己的理解: 1、新建Thread HandlerThread;2、指定ServiceHandler運...
    畫十閱讀 187評論 0 0
  • 今天輕松跑步,跑了六公里,田園風(fēng)光也一覽無遺,住的地方算是重劃區(qū),所以跑步的環(huán)境沒廣東這么大。 回臺七天,跑步四次...
    AD_Chen閱讀 687評論 0 3

友情鏈接更多精彩內(nèi)容