Scala/例外処理

    try {
      throw new Throwable("hogehoge")
    } catch {
      case t: Exception =>
        println("e")
        t.printStackTrace()
      case t: Throwable =>
        // こっちに来る
        println("t")
        t.printStackTrace()
    }
 
    try {
      throw new Exception("piyopiyo")
    } catch {
      case t: Exception =>
        // こっちに来る
        println("e")
        t.printStackTrace()
      case t: Throwable =>
        println("t")
        t.printStackTrace()
    }

try-catch 構文の戻り値

ifと同様にtry-catch 構文 も戻り値を持たせられる。

catch ブロックでの最後に評価された値が戻る。 例外が発生しなければ try で最後に評価された値が戻る。

var a = try {
  throw new Throwable("hogehoge")
} catch {
  case e: Exception =>
    println("e")
    e.printStackTrace()
    "e"
  case t: Throwable =>
    // こっちに来る
    println("t")
    t.printStackTrace()
    "t"
}
println(a) //=> "t"
a = try {
  throw new Exception("piyopiyo")
} catch {
  case e: Exception =>
    // こっちに来る
    println("e")
    e.printStackTrace()
    "e"
  case t: Throwable =>
    println("t")
    t.printStackTrace()
    "t"
}
println(a) //=> "e"

finally

Java 同様に finally がある

try {
  throw new Throwable("hogehoge")
} catch {
  println("catch")
} finally {
  println("finally")
}

finally のブロックでの評価値は捨てられる。