Scala/例外処理

Scala/例外処理

  • Java 同様 try catch finaly
  • 最近の言語よろしく例外はすべて「非チェック例外」である
  • try catch 機構に戻り値を設定できる
  • 例外の型は case で分岐できる。これは 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 のブロックでの評価値は捨てられる。

scala/exception_handling.txt · 最終更新: 2020-08-03 13:15 by ore