DEV Community

kaede
kaede

Posted on

Kotlin 基礎 Part 2 -- Exception(例外) の投げ方

why

例外についての知見が

API にリクエストを投げて駄目だったときに備えて作っておくべきもの

程度しかなかったので


Exception (例外) とは?

https://www.udemy.com/course/kotlinmasterclass/learn/lecture/16673664#overview

Udemy の Kotlin Master Class で学習した。

予想しないことが起こった時に出るもので
一度例外が出ると、そこからシステムは復帰できないらしい。

Stacktrace という Exception の前にどこの関数が動いたかの情報が出る.


普通に起こる Exception

    print("text".toInt())

java.lang.NumberFormatException: For input string: "text"
Enter fullscreen mode Exit fullscreen mode

String を Int にすると NumberFormatException が出る。

at com.example.springboot.PersonHandler.getPersons(Resource.kt:18) 
Enter fullscreen mode Exit fullscreen mode

同時に Stacktrace が出る。
ここでは、 PersonHandler の getPersons ( Resource.kt の 18 行目 ) で起きたという情報が取れた。


try/catch で Exception を握り潰して簡易エラーメッセージだけだしてアプリを続行する

    try {
      print("text"?.toInt())
    } catch (e: Exception) {
      println("Exception Occurred!")
      println(e.localizedMessage)
    }
Enter fullscreen mode Exit fullscreen mode

先程の NumberFormatException を起こすコードを try の内部にいれて
Exception がでたら Exception の localizedMessage がでるようにした。

Exception Occurred!
For input string: "text"
Enter fullscreen mode Exit fullscreen mode

localizedMessage だとこの最小限のエラーメッセージが出る。
また、通常 Exception がでたらアプリは終了する。
しかし今回は try で予測して Exception を catch している。
なのでアプリは終了せず、次の行が実行できた。


Exception を握りつぶしながら詳細なスタックトレースも出す

catch (e: Exception) {
      println("Exception Occurred!")
      e.printStackTrace()
      println(e.localizedMessage)
    }
Enter fullscreen mode Exit fullscreen mode

e.printStackTrace を catch の中にいれると
Exception を握りつぶしながら、詳細なスタックトレースも出せる。

Image description

再び見慣れたエラーの赤い文字が出るようになる

その後に finally を書くと、try がうまくいっても Error がでてもどのみち動く。初期化処理とかを書くのかな?


状況や引数不足で例外を投げるようにする

オリジナルの例外メッセージを投げられる。

    throw IllegalStateException("なんかちがう")
Enter fullscreen mode Exit fullscreen mode
java.lang.IllegalStateException: なんかちがう
Enter fullscreen mode Exit fullscreen mode

https://programmer-life.work/java/illegalstateexception

IllegalStateException は不適切な状況の時に投げるべき Exception

https://kotlinlang.org/docs/exceptions.html#the-nothing-type

    val name = null
    name ?: throw IllegalArgumentException("Name required")
Enter fullscreen mode Exit fullscreen mode
java.lang.IllegalArgumentException: Name required
Enter fullscreen mode Exit fullscreen mode

IllegalArgumentException は引数が不適切な時に投げる Exception

このように、その場にふさわしい名前の例外を投げよう!


条件に応じてオリジナルな例外を投げる

Runtime Exception を拡張して、HogeIdNotFoundException のようなカスタムエラーも作ることができる。要検証。

HogeId がない場合に throw HogeIdNotFoundException() をする。


まとめ

String が Int に変換されたり、予想外のことが起こると
Kotlin は Exception を吐いてアプリが終了する。

しかし、予想外のことが起きそうな行を try の内部で書いて
catch で受け止めれば、アプリを終了せずに続行することができる。

一方、握りつぶしたところでその処理は行われない。データの不整合などが起きると困るので、catch の中には stacktrace を出すようにして後でログで確認できるようにしよう!

また、Usecase で条件に応じて IllegalStateException や IllegalArgumentException を throw すれば、まずいものが入る前にアプリを終了するようにできる。

さらに、Runtime Exception は拡張できるので、自分のオリジナルの Exception を作るとエラーログが追いやすくなるだろう。

Latest comments (0)