LoginSignup
1
2

More than 5 years have passed since last update.

Scalaでの例外処理

Posted at

はじめに

新米のわっちがScalaで書く例外処理の書き方について。
この前話をしていて例外処理を処理の流れに含めるかどうかの違いが一番大きいのかなって気づいたっぽい。

書き方の具体例

Javaっぽい

処理に例外処理を含めない感じ。
あとtryの値をvalでキャッチしないっぽい。

れーがい.scala

    var contents: BufferedSource = null
    try {
      contents = scala.io.Source.fromURL("htp://www.yahoo.co.jp")
    } catch {
      case e: Exception =>
        printWithLogger(e)
    }
    if (contents != null) {
      val linesAddedWords = contents.getLines().map(_.concat("add words after the line"))
      saveToDatabase(linesAddedWords)
    }

Scalaっぽい

処理に例外処理を含めるっぽい感じ。

れーがい.scala

   Try {
      scala.io.Source.fromURL("htp://www.yahoo.co.jp")
    }.map(_.getLines.map {
      _.concat("add words after the line")
    }) match {
      case Success(s) =>
        saveToDatabase(s)
      case Failure(e) =>
        printWithLogger(e)
    }

補足

まとめ

Javaっぽい例外処理とScalaっぽい例外処理について書いてみた。
例外処理の考え方について学びたい。

1
2
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
1
2