22
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Tryとパターンマッチで例外処理を整理する

Last updated at Posted at 2017-12-02

例外を投げるライブラリを使おうとすると途端に泥臭くなりがちです。
渡された数値で日付を生成するときなど、DateTimeExceptionを考慮しtry-catchで分岐して…などやり始めるとコードの見通しが悪くなります。

####例題
2組の年・月・日の数値から、より未来の日付を導く

コテコテにtry-catch
def dateOrMin(y:Int, m:Int, d:Int): LocalDate = {
  try {
    LocalDate.of(y,m,d)
  } catch {
    case _: Throwable => LocalDate.MIN
  }
}

val d1 = dateOrMin(2017,0,1)
val d2 = dateOrMin(2017,12,3)

if (d1 == LocalDate.MIN && d2 == LocalDate.MIN){
  throw new DateTimeException("どっちも不正な日付です…")
}else if(d1 isAfter d2) {
  d1
} else {
  d2
}

scala.util.Try が便利でした

スッキリ
def tryDate(y:Int, m:Int, d:Int): Try[LocalDate] = Try{ LocalDate.of(y,m,d) }

(tryDate(2017,0,1),tryDate(2017,0,1)) match {
  case (Success(d1),Success(d2)) => if(d1 isAfter d2) d1 else d2
  case (Success(d1),Failure(_)) => d1
  case (Failure(_),Success(d2)) => d2
  case _ => throw new DateTimeException("どっちも不正な日付です…")
}

TryはtoEithertoOptionを備えているので、forの中で扱うにもよいです。

22
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
22
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?