Re: Best practice for exceptions
Re: Best practice for exceptions
- Subject: Re: Best practice for exceptions
- From: Ali Ozer <email@hidden>
- Date: Tue, 26 Feb 2002 15:30:22 -0800
On Tuesday, February 26, 2002, at 09:22 AM, Drew McCormack wrote:
>
I was wondering if someone with plenty of experience would like to
>
explain how they utilize exceptions in their cocoa apps. I can never
>
figure out when I should throw an exception, and when I should, for
>
example, set a flag and put details of the failure in a string to
>
return to the caller. Is there a general consensus on this?
As far as the Cocoa APIs go: They do not use exceptions as a standard
part of the API. Exceptions are reserved more for, well, exceptional
situations that usually are not planned for, or for assertion failures
where something goes wrong, usually as a result of programming or logic
error (array index out of bounds, or similar parameter errors, assuming
the recipient checks for those error conditions).
Expected errors, including usual runtime failures or failures due to
user errors, are reported via the standard API techniques, such as nil,
BOOL, or error code returns, and in general apps do not need to catch
exceptions as a result of Cocoa calls. If an exception is raised, it
ends up in the top level exception handler, which logs it; or you can
deal with it by registering a top-level handler if you wish. By the time
your app ships, various issues that were causing the exceptions have
hopefully been addressed, so no shipping code should have to catch
exceptions out of Cocoa calls.
>
For example, I am writing an expression parser. If the parser comes
>
across a syntax error in the expression, which was entered by the user,
>
should I throw an exception, or simply return an error code to the
>
caller, with a message to display to the user. It's not an exception in
>
the sense that something completely unexpected has happened, since user
>
error is to be expected. On the other hand, exceptions seem to be more
>
elegant than setting a failure flag and adding an extra 'message'
>
argument to function, like in the old days.
As Erik Buck points out exceptions can certainly come in handy within
implementations of classes, and in fact, an expression parser is a great
example of when to use exceptions. As far as the external API to your
parser, you can choose to raise exceptions, in which case you should
document the exceptions as API, or you can contain the exceptions and
return error codes. As mentioned above, Cocoa APIs prefer the latter.
Ali
_______________________________________________
cocoa-dev mailing list | email@hidden
Help/Unsubscribe/Archives:
http://www.lists.apple.com/mailman/listinfo/cocoa-dev
Do not post admin requests to the list. They will be ignored.