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

 

posted @ 2018-01-28 20:51  AK47Sonic  阅读(568)  评论(0编辑  收藏  举报