以下の内容はhttps://blog.beatdjam.com/entry/2018/07/21/013059より取得しました。


【Kotlin】Kotlinで複数の例外をキャッチする

Java7以降で対応されている複数例外のマルチキャッチ機能が、
Kotlinでは利用できなかったので調べた。

書き方

  • Java6以前の書き方
try {
    ...
} catch(IOException e) {
    ...
} catch(ClassNotFoundException e) {
    ...
}
  • Java7以降の書き方
try {
    ...
} catch(IOException | ClassNotFoundException e) {
    ...
}
  • Java7以降の書き方に似た処理をKotlinで書く場合
try {
   ...
} catch (e: Exception) {
    when(e) {
        is IOException, is ClassNotFoundException -> {
            ...
        }
        else -> throw e
    }
}

説明

catchですべてのExceptionをcatchしたあと、whenで対応する例外の処理を書くだけ。
2個以下の場合だとちょっと冗長になるけど、3個以上の例外に同じ処理を適用する場合は多少スッキリするはず。

参考 : How to catch many exceptions at the same time in Kotlin - Stack Overflow




以上の内容はhttps://blog.beatdjam.com/entry/2018/07/21/013059より取得しました。
このページはhttp://font.textar.tv/のウェブフォントを使用してます

不具合報告/要望等はこちらへお願いします。
モバイルやる夫Viewer Ver0.14