In the development process, often to use exception handling, to prevent the sudden collapse of the program, in the java,c++ throw exception, and assertion processing, then in OC is how to deal with the exception?
1. Nsassert
See how iOS is defined
#if !defined (_nsassertbody)#define Nsassert (condition, desc, ...) Do { __pragma_push_no_extra_arg_warnings if (! (condition)) {[ [Nsassertionhandler Currenthandler] handlefailureinmethod:_cmd object: Self file: [NSString stringwithutf8string:__file__] LINENUMBER:__LINE__ Description: (DESC), # #__VA_ARGS__]; } __pragma_pop_no_extra_arg_warnings while (0)#endif
Specific usage:
If condition is false, throws an exception
int 0 ; Nsassert (a! =0,@ "x must not being zero", __func__);
Exception information thrown:
£ º47.692 audiodemo[1928 in-[gnviewcontroller touchesbegan:withevent:],/users/geng/desktop/programe/audio/audiodemo/ AUDIODEMO/GNVIEWCONTROLLER.M:
2. Since Nsassert references self, it is easy to cause circular references at block time, so it is common to use the following assertion
#define Nscassert (condition, desc, ...) Do { __pragma_push_no_extra_arg_warnings if (! (condition)) {[ [Nsassertionhandler Currenthandler] handlefailureinfunction:[nsstring stringwithutf8string:__pretty_ FUNCTION__] file:[nsstring stringwithutf8string:__file__] linenumber:__line__ Description: (DESC), # #__VA _ARGS__]; } __pragma_pop_no_extra_arg_warnings while (0)
3.throw Throw exception
// Throw Exception if Ten { nsexception* exp = [nsexception exceptionwithname:@ "num >" Reason: @" num > Ten " Userinfo:nil]; @throw exp; }
The printing results are:
-- One- + -: +:33.999exceptiondemo[2136: 60b]4 -- One- + -: +:34.296exceptiondemo[2136: 60b]5 -- One- + -: +:34.775exceptiondemo[2136: 60b]6 -- One- + -: +:35.254exceptiondemo[2136: 60b]7 -- One- + -: +:35.813exceptiondemo[2136: 60b]8 -- One- + -: +:36.429exceptiondemo[2136: 60b]9 -- One- + -: +:36.983exceptiondemo[2136: 60b]Ten -- One- + -: +:37.597exceptiondemo[2136: 60b] * * * terminating app due to uncaught exception'num > Ten', Reason:'num > Ten'FirstThrowCall stack: (0Corefoundation0x017ec1e4__exceptio
This is a direct crash, if you want to not crash, continue to execute, then you need to use a try Catch
@try { [self.mybox Pushin]; } @catch (NSException *exception) { NSLog (@ "%@", Exception.reason); } @finally { [Self.mybox printnumber]; }
This will not break down.
IOS exception Handling (-)