Question:
What's the best way to throw an exception in objective-c/cocoa?
Answer:
Use [NSException raise:format:] as follows:
[NSException raise:@"Invalid foo value" format:@"foo of %d is invalid", foo];
此时控制台会Log:
*** Terminating app due to uncaught exception 'Invalid foo value', reason: 'foo of 9999 is invalid'
*** First throw call stack:
(
0 CoreFoundation 0x0083dca6 __exceptionPreprocess + 182
1 libobjc.A.dylib 0x004e18bf objc_exception_throw + 44
2 CoreFoundation 0x0083dbcd +[NSException raise:format:] + 141
3 Exception 0x0000e9fb -[ViewController viewDidLoad] + 139
4 UIKit 0x00d3f2f4 -[UIViewController loadViewIfRequired] + 771
5 UIKit 0x00d3f5e5 -[UIViewController view] + 35
6 UIKit 0x00c3a009 -[UIWindow addRootViewControllerViewIfPossible] + 66
7 UIKit 0x00c3a47b -[UIWindow _setHidden:forced:] + 314
8 UIKit 0x00c3a6f8 -[UIWindow _orderFrontWithoutMakingKey] + 49
9 UIKit 0x00c4931e -[UIWindow makeKeyAndVisible] + 80
10 UIKit 0x00be6e18 -[UIApplication _callInitializationDelegatesForMainScene:transitionContext:] + 3159
11 UIKit 0x00be9efb -[UIApplication _runWithMainScene:transitionContext:completion:] + 1507
12 UIKit 0x00c02742 __84-[UIApplication _handleApplicationActivationWithScene:transitionContext:completion:]_block_invoke + 59
13 UIKit 0x00be8c3e -[UIApplication workspaceDidEndTransaction:] + 29
14 FrontBoardServices 0x030bcbce __37-[FBSWorkspace clientEndTransaction:]_block_invoke_2 + 43
15 FrontBoardServices 0x030bc834 __40-[FBSWorkspace _performDelegateCallOut:]_block_invoke + 54
16 FrontBoardServices 0x030ce455 __31-[FBSSerialQueue performAsync:]_block_invoke + 26
17 CoreFoundation 0x00762540 __CFRUNLOOP_IS_CALLING_OUT_TO_A_BLOCK__ + 16
18 CoreFoundation 0x007577d3 __CFRunLoopDoBlocks + 195
19 CoreFoundation 0x00756f38 __CFRunLoopRun + 936
20 CoreFoundation 0x007568cb CFRunLoopRunSpecific + 443
21 CoreFoundation 0x007566fb CFRunLoopRunInMode + 123
22 UIKit 0x00be8555 -[UIApplication _run] + 571
23 UIKit 0x00bebba5 UIApplicationMain + 1526
24 Exception 0x0000eddd main + 141
25 libdyld.dylib 0x02af1ac9 start + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
But in fact, Apple does not recommend that we throw an exception, which consumes too much resources.
Reference:
http://stackoverflow.com/questions/324284/throwing-an-exception-in-objective-c-cocoa