Re: Exception handling
Re: Exception handling
- Subject: Re: Exception handling
- From: Quincey Morris <email@hidden>
- Date: Wed, 13 Jun 2018 19:53:26 -0700
On Jun 13, 2018, at 19:22 , Casey McDermott <email@hidden> wrote:
>
> Nearly always, the event loop is the best place to escape to.
This is not how current thinking goes, unless you mean something different from
what I think you’re saying.
If you’re implementing sanity (“should not happen”) checks, then the belief
that it’s safe to shrug and return to the event loop is just false. It would be
true if no significant state was preserved across event loop iterations, but
that’s not nearly true — and likely extremely *un*true for those APIs and
libraries that are complicated enough for the checks to fail sometimes. It’s
simply not safe to branch out of lower-level code unless *all* of the code has
been explicitly designed for that usage style.
It’s better to simply log the error and crash.
For recoverable errors in Obj-C code, you’re better off just doing the work of
returning a “success or not” value along with a NSError out parameter. It’s a
bit of grunt work to add this to existing code, but it’s probably worthwhile.
(This would include having failable class init’s that have an outError
parameter, which is not a common pattern, though it should be.)
The real problem comes, however, when you consider multiple threads. You can
certainly catch NSExceptions in a sendEvent: override on the main thread, but
in modern Cocoa programming there are many situations where you’re running your
code on a background thread (e.g. GCD), and there’s not always an event loop or
any good place to catch exceptions.
The situation with C++ exceptions is a bit different. You can basically do
whatever you want with those (including using them for flow control), but
there’s still nowhere central to catch uncaught exceptions, and you still have
to worry about multithreading.
I may be out on my lonesome here, but if you want a robust app, I really think
you have exactly 2 error handling patterns:
1. Returning false/nil with an outError parameter for recoverable errors, and
always testing the result at every level.
2. Throwing NSExceptions for unrecoverable errors, and letting the app crash
immediately.
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden