13

I recently started learning Objective-C, and I am working on an iOS app as an exercise, anyway, I want to handle overflow by throwing exception (I come from a Java background), I searched the reference there is only NSException, but then I read in the section that say topics about exception handling, and they said to use NSError, I read the reference but they had the same protocol and methods, so what's the difference between them? And which is better?

Also, I want to create my own exception or error class, are there any methods or fields that I should include? (Like when implementing the Exception interface in Java). Thanks

hakuna matata
  • 3,243
  • 13
  • 56
  • 93

1 Answers1

23

NSError is designed for non-fatal, recoverable errors. The problems that are designed to be captured by an NSError are often user errors (or are errors that can be presented to the user), can often be recovered from (hence -presentError: and NSErrorRecoveryAttempting), and are usually expected or predictable errors (like trying to open a file that you don't have access to, or trying to convert between incompatible string encodings).

NSException is designed for potentially fatal, programmer errors. These errors are designed to signify potential flaws in your application where you have not correctly checked the pre-conditions for performing some operations (like trying to access an array index that is beyond its bounds, or attempts to mutate an immutable object). The introduction to the Exception Programming Guide explains this a little bit.

一二三
  • 21,059
  • 11
  • 65
  • 74
  • Ohh, Okay. So for handling overflow I should use Exception, since its a flaw in my application? – hakuna matata Jun 19 '12 at 13:46
  • 1
    Yes, if its an unexpected situation that should not occur with correct code. – 一二三 Jun 19 '12 at 16:00
  • Ohh Thanks, but what about the second part of the question, creating my own Exception class? – hakuna matata Jun 19 '12 at 16:06
  • 2
    Subclasses of `NSException` are uncommon: exceptions are typically differentiated by their name (using `+exceptionWithName:reason:userInfo:`), rather than their class. However, you can `@raise` any kind of object as an exception (`NSString`, `NSObject`, anything), there are no special interface requirements (although, this isn't recommended). – 一二三 Jun 20 '12 at 13:41
  • So in this respect, NSError == java checked exception, NSException == Java unchecked exception (RuntimeException) – nbransby Nov 13 '12 at 10:46
  • No. Objective-C doesn't have checked exceptions, and `NSError` does not trigger exception handlers. – 一二三 Nov 14 '12 at 11:51
  • 1
    More like NSError==java unchecked Exception, NSException== java Error – awiebe Dec 16 '12 at 07:00