Scalaの例外の基本
基本的なことですが、例外が発生した場合、後続の処理がどうなるのか
きちんと見ていきます。
3つのメソッドtestA, testB, testCを作成して
それぞれ下記のメソッドを呼び出します。
そしてtestCでは例外を発生されます。
testA -> testB -> testC(例外発生!)
実際のコードはこんな感じです。
import scala.util.{Failure, Success, Try} // testAメソッドを呼ぶ val result = Try { testA println("ここは呼ばれません!!") } // 例外があった場合はエラーメッセージを表示 result match { case Success(e) => println("Success!!") case Failure(e) => println(e) } // testBメソッドを呼ぶ def testA: Unit = { println("Here is testA method") testB println("ここは呼ばれません!!") } // testCメソッドを呼ぶ def testB: Unit ={ println("Here is testB method") testC println("ここは呼ばれません!!") } // 例外発生! def testC: Unit = { println("Here is testC method") throw new Exception ("Exception") println("ここは呼ばれません!!") }
結果はこんな感じになります。
Here is testA method Here is testB method Here is testC method result: scala.util.Try[Unit] = Failure(java.lang.Exception: Exception) java.lang.Exception: Exception
ここで注目して欲しいのは、testCメソッドで例外発生後は
ここは呼ばれません!!
が結果に表示されていませんね。
例外がスローされると後続の処理は実行されないんですね。
「あれー、でも例外発生時も後続処理したいんだけどなぁー」
って時どうするか!
そこでtry,catchの登場です!
続く。