將異常轉換為 Either 或 Option 型別

要將異常轉換為 EitherOption 型別,你可以使用 scala.util.control.Exception 中提供的方法

import scala.util.control.Exception._

val plain = "71a"
val optionInt: Option[Int] = catching(classOf[java.lang.NumberFormatException]) opt { plain.toInt }
val eitherInt = Either[Throwable, Int] = catching(classOf[java.lang.NumberFormatException]) either { plain.toInt }