Java Exception Handlingメモ

Amazonに勧められたので2013年の8月に買ったんだけど、なんかamazon.co.jpに売ってないなあ。

Javaに特化した話題もあれば、より一般的な話題もある。心に残った一節。

Designing exception handling for an application means deciding how the application should react to errors to assure the application stays healthly.

(Exception Handling Helps Preserve Application Health)

(例外処理を設計するということは、アプリケーションがその健全性を保証するために、 エラーに対してどのように反応すべきかを決めることを意味する)

例外を投げる側が、何が起こったという情報を収集する一方で、例外をキャッチする側は、 その例外に対してどう反応すべきかを決めなければいけない。 例えばアプリケーションを終了するのか、リクエストを中断するのか、リトライするのか。 他のシステムや人間に通知するのか、等々。

How an application should react to errors depends on what state it is in.

(Application States)

  • not running
  • initializing
  • running
  • temporarily unavailable
  • shutting down

例えばinitializingでエラーが発生したらshutting downに移行すべきだが、 runningでエラーが出た場合は、その処理だけを中断して継続可能か、shutting downに移行するか、temporarily unavailableに移行するか(一時的なリソース不足)。

The origin of an error influences how the application can react to them.

(Error origins)

  • Client Errors
  • Service Errors
  • Internal Errors
  • (Temporary Internal Errors)

例えば、Service Errors(アプリケーションが利用する外部のサービスエラー) であれば、リトライするか、あるいは別のサーバーにリクエストするといった対応もありえる。

As you can see, determining the true origin of an error may not always be possible at the point where the error is detected.

そしてそれらは、例外を検出した箇所で決定できるとは限らない(複数の箇所から呼び出される処理内で検出された場合のように)。適切な文脈を決定するために、例外を上位に伝播する必要がある。