Help us understand the problem. What is going on with this article?

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

More than 1 year has passed since last update.

例外を投げるライブラリを使おうとすると途端に泥臭くなりがちです。
渡された数値で日付を生成するときなど、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の中で扱うにもよいです。

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away