Scala Try Catch Finally

Posted AK47Sonic

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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最低

object ExceptionCatchDemo extends App {

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

  println(testTryCatchFinally)


}

运行结果:2

 

以上是关于Scala Try Catch Finally的主要内容,如果未能解决你的问题,请参考以下文章

关于try catch finally

java中的“try - catch -finally”结构中的“finally”都有哪些用途

try-catch-finally 中哪个部分可以省略?try-catch-finally 中,如果 catch 中 return 了,finally 还会执行吗?

对try catch finally的理解

try catch和finally

try{ } catch{ } finally{ }