定食屋おろポン

おろしポン酢と青ネギはかけ放題です

Swiftのエラーハンドリング

Objective-Cにおいては、「Exceptionは処理するな」が鉄則です。 つまり、

  • 「例外を投げるのは致命的な問題(復旧不可能な問題)が発生したときのみ」
  • 「例外を受け取ったらアプリを終了させろ」

というポリシーです。

これは、そもそも例外を受け取ってキャッチ句にジャンプすること自体が、ARCによるメモリ管理を壊してしまうことに起因しています。(と理解しています。)

http://clang.llvm.org/docs/AutomaticReferenceCounting.html#exceptions

By default in Objective C, ARC is not exception-safe for normal releases:

ところで、Swiftではどうでしょうか。 Swiftのリファレンスを眺めてもエラーハンドリングに頁が割かれていません。

上記のポリシーはSwiftでも同様であり、「例外を受けとったらアプリを殺せ」はまったく変わらないようです。

https://devforums.apple.com/thread/227375?start=25&tstart=0

Cocoa uses exceptions only for effectively unrecoverable error cases. In most circumstances it doesn't make sense to try to catch an exception and continue execution; ARC will leak references, and framework state will be inconsistent. You should check for exceptional circumstances before invoking methods that may throw exceptions.

SwiftもGCではなくARCによるメモリ管理を採用しているため、仕方がないですね。