29

The try{}catch construct is common to C++, Java & related languages. In the iOS SDK is there and any functionality like this?

Moshe
  • 56,717
  • 76
  • 267
  • 423
Sam007
  • 1,385
  • 3
  • 17
  • 31
  • possible duplicate of [Try-catch exception handling practice for iPhone/Objective-C](http://stackoverflow.com/questions/3678438/try-catch-exception-handling-practice-for-iphone-objective-c) – ceejayoz Apr 18 '11 at 14:06
  • 6
    Some advice since it looks like you're coming over from the Java world: in iOS exceptions are rarely used for program control. An exception almost always means that the programmer did something wrong and it should be fixed. http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/ErrorHandlingCocoa/CreateCustomizeNSError/CreateCustomizeNSError.html#//apple_ref/doc/uid/TP40001806-CH204-BAJIIGCC – kubi Apr 18 '11 at 14:13
  • 2
    Here's a better link that describes the role of exceptions in Cocoa/iOS: http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/ErrorHandlingCocoa/CreateCustomizeNSError/CreateCustomizeNSError.html#//apple_ref/doc/uid/TP40001806-CH204-BAJIIGCC – kubi Apr 18 '11 at 14:20

1 Answers1

92
@try {
    // Try something
}
@catch (NSException * e) {
    NSLog(@"Exception: %@", e); 
}
@finally {
    // Added to show finally works as well
}
Neil Knight
  • 45,890
  • 23
  • 126
  • 186
  • 4
    Curious: is there EVER a situation where the exception caught would not be of type `NSException`? More importantly, is there ever a situation in which the `NSLog` could blow up? If you think this is a different question, let me know and I'll ask it properly. – Dan Rosenstark Jan 12 '12 at 19:12
  • Yes, you can capture a specific exception or a custom exception. Check out the example under "Catching Different Types of Exception". http://developer.apple.com/library/ios/#documentation/cocoa/conceptual/objectivec/Chapters/ocExceptionHandling.html – IanStallings Nov 29 '12 at 04:41