zoukankan      html  css  js  c++  java
  • Scala Try Catch Finally

    Scala Try Catch Finally:

    在Java中返回值优先级顺序:finally最高, try,catch 选其一,try中抛异常,返回catch,不抛异常,返回try,

    public class ExceptionDemo {
    
        public static void main(String[] args) {
            System.out.println(callMD());
    
        }
    
        public static int callMD() {
            try {
    //            throw new Exception();
                return 1;
            } catch (Exception e) {
                return 2;
            } finally {
                return 3;
            }
        }
    
    }

    Scala模仿Java:

    object ExceptionCatchDemo extends App {
    
      def testTryCatchFinally: Int = {
        try { throw new Exception();} catch { case _ => return 2 } finally { return 3 }
      }
    
    
      println(testTryCatchFinally)
    }

    运行结果:3

    在Scala中返回值优先级顺序:try,catch 选其一,try中抛异常,返回catch,不抛异常,返回try,finally最低

    补充: 从scala语言规范来看,try-catch-finally表达式也是有返回值的,且返回值主要是取决于try 和catch里的最后一行表达式,而finally被认为是做一些收尾的工作的,不应该在里面去改变返回结果。编译器在finally块最后自行增加了一个返回Unit类型的值(),编译器认为finally块里的逻辑是一个“procedure”,一定要满足Unit

    object ExceptionCatchDemo extends App {
    
      def testTryCatchFinally: Int = {
        try { throw new Exception() } catch { case _ => 2 } finally { 3 }
      }
    
      println(testTryCatchFinally)
    
    
    }
    

    运行结果:2

  • 相关阅读:
    alias这个命令还是很有用的
    为什么不推荐用破解版的winrar
    chrome headless
    关于PDF的一些书籍
    PDF的一些工具
    3DPDF是个什么东西?
    你可能不知道的pdf的功能
    为什么一些公司把dwg文件转化为pdf
    关于pdf阅读器的选择
    接外包怎么保护自己的作品
  • 原文地址:https://www.cnblogs.com/AK47Sonic/p/8372350.html
Copyright © 2011-2022 走看看