Scala Try Catch Finally
阿新 • • 發佈:2018-01-28
demo span 順序 extend stat out post final row
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