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 + 1821 libobjc.A.dylib 0x004e18bf objc_exception_throw + 442 CoreFoundation 0x0083dbcd +[NSException raise:format:] + 1413 Exception 0x0000e9fb -[ViewController viewDidLoad] + 1394 UIKit 0x00d3f2f4 -[UIViewController loadViewIfRequired] + 7715 UIKit 0x00d3f5e5 -[UIViewController view] + 356 UIKit 0x00c3a009 -[UIWindow addRootViewControllerViewIfPossible] + 667 UIKit 0x00c3a47b -[UIWindow _setHidden:forced:] + 3148 UIKit 0x00c3a6f8 -[UIWindow _orderFrontWithoutMakingKey] + 499 UIKit 0x00c4931e -[UIWindow makeKeyAndVisible] + 8010 UIKit 0x00be6e18 -[UIApplication _callInitializationDelegatesForMainScene:transitionContext:] + 315911 UIKit 0x00be9efb -[UIApplication _runWithMainScene:transitionContext:completion:] + 150712 UIKit 0x00c02742 __84-[UIApplication _handleApplicationActivationWithScene:transitionContext:completion:]_block_invoke + 5913 UIKit 0x00be8c3e -[UIApplication workspaceDidEndTransaction:] + 2914 FrontBoardServices 0x030bcbce __37-[FBSWorkspace clientEndTransaction:]_block_invoke_2 + 4315 FrontBoardServices 0x030bc834 __40-[FBSWorkspace _performDelegateCallOut:]_block_invoke + 5416 FrontBoardServices 0x030ce455 __31-[FBSSerialQueue performAsync:]_block_invoke + 2617 CoreFoundation 0x00762540 __CFRUNLOOP_IS_CALLING_OUT_TO_A_BLOCK__ + 1618 CoreFoundation 0x007577d3 __CFRunLoopDoBlocks + 19519 CoreFoundation 0x00756f38 __CFRunLoopRun + 93620 CoreFoundation 0x007568cb CFRunLoopRunSpecific + 44321 CoreFoundation 0x007566fb CFRunLoopRunInMode + 12322 UIKit 0x00be8555 -[UIApplication _run] + 57123 UIKit 0x00bebba5 UIApplicationMain + 152624 Exception 0x0000eddd main + 14125 libdyld.dylib 0x02af1ac9 start + 1)libc++abi.dylib: terminating with uncaught exception of type NSException
但實際上Apple並不建議我們拋出異常,耗費的資源太大。
Reference:
http://stackoverflow.com/questions/324284/throwing-an-exception-in-objective-c-cocoa