Skip to content

例外ハンドラと失敗の伝搬

コルーチンのエラーハンドリングは, めんどうくさい.

CoroutineExceptionHandler

公式リファレンスに

Exception Handling and Supervision

CoroutineExceptionHandler context element on a root coroutine can be used as generic catch block for this root coroutine and all its children where custom exception handling may take place

とあるように CoroutineExceptionHandler は, ルートのコルーチンに子コルーチンの投げた例外をハンドリングさせるために使う.

デフォルトだと, Thread.uncaughtExceptionHandler が使われて1

Exception in thread "DefaultDispatcher-worker-2 @coroutine#2" java.lang.IndexOutOfBoundsException

のような標準出力がされるのみで, エラーに気づけない.

CoroutineExceptionHandlerServiceLoader 経由でも設定できる23ので, ちゃんとアプリケーションのロガーで WARN か ERROR が残るようにしておくとよい.

CancellationException

同じのスコープのコルーチンの失敗などによってコルーチンがキャンセルされると, CancellationException が投げられる.

このとき, 終了処理などハンドリングが必要なら, ちゃんと try-catchtry-finally を書かないといけない.

このハンドリングに, CoroutineExceptionHandler は使えないのも注意.


こんなスクリプトを動かしてみると, なんとなく分かる.


Posted: 2020-07-27
Last update: 2021-03-02