iOS was forgotten by developers in the corner of the nsexception-actually it's very powerful

Source: Internet
Author: User
Tags throw exception

Reproduced from Http://www.jianshu.com/p/05aad21e319eiOS by developers forgotten in the corner of the nsexception-actually it is very powerfulwords 597 read 968 comments 4 likes What is NSException?

The most familiar stranger, this is my overview of nsexception, why do you say so? In fact, many developers come into contact with nsexception frequency very frequently, but many people do not know what is nsexception, do not know how to use NSException. Let's start with the nsexception from a single beginning.


Crash. png

The above picture must be a stranger to everyone! (Lying trough, the program crashes again).

In fact, the console output log information is nsexception generated, once the program throws an exception, the program will crash, the console will have these crash logs.

Basic usage of NSException

下面代码就会让你的程序崩溃

 //exception name nsstring *exceptionName = @ "Custom Exception"; //the cause of the exception nsstring *exceptionreason = @ "I was too handsome, so the program collapsed"; //exception information nsdictionary *exceptionuserinfo = NIL; nsexception *exception = [nsexception exceptionWithName: Exceptionname Reason:exceptionreason Userinfo:exceptionuserinfo]; nsstring *aboutme = @ "too Handsome"; if ([Aboutme isequaltostring:@ "too Handsome"]) { //throw exception  @throw exception;}       

崩溃如下


Custom exception crashes. Why PNG says NSException is strong

NSException control the life of the program, the collapse of the program is nsexception to control, you say NSException not strong? Then why nsexception the program to crash? In fact, the main starting point is to let developers know where the code is problematic.

Here's a practical tip for two nsexception.

    • 1, if you encapsulate a set of SDK, to indicate where the error, then you can use NSException. Just like the code in the basic usage of nsexception above.
    • 2, can be used to catch exceptions, to prevent the program crashes. When you realize that a piece of code might be in danger of crashing, you can prevent the program from crashing by catching exceptions. The code is as follows
 nsstring *nilStr = NIL;    nsmutablearray *arraym = [nsmutablearray array];  @try {//if the code in @try causes the program to crash, it will come to @catch //insert a nil into a mutable array, this line of code must be problematic [Arraym addobject:nilstr];}  @catch (nsexception *exception) { //if there is a problem with the code in @try (resulting in a crash), it will come to @catch //Here you can do the appropriate processing operation //if you want to throw an exception (let the program crash), write @throw exception} //@finally is bound to be executed //you can do something about it here.}     
    • 3, the most practical one of the technical point is the use of classification (category) + runtime + abnormal capture to prevent some of the foundation's common methods of improper use caused by the crash. The principle is to use category, runtime to exchange two of methods, and in the method to catch the exception to the corresponding processing. (Here you need to know some knowledge about the runtime, if the runtime is not familiar with friends, you can first understand the next runtime method Exchange). Below is the approximate method of use.

添加分类,利用runtime交换方法

//Nsmutablearray+extension.mCategorytest//Created by Mac on 16/10/6.Copyright? 2016 Chenfanfang. All rights reserved.//#import"Nsmutablearray+extension.h"#import<objc/runtime.h>@implementationNsmutablearray (Extension) + (void) Load {Class Arraymclass =Nsclassfromstring (@ "__nsarraym");Gets the method of adding elements to the system methods AddObject = Class_getinstancemethod (Arraymclass,@selector (addobject:));Get our custom add Element method Avoidcrashaddobject = Class_getinstancemethod (Arraymclass,@selector (avoidcrashaddobject:));Swap two methodsWhen you call AddObject, it's actually called Avoidcrashaddobject//when you call Avoidcrashaddobject, is actually called AddObject method_exchangeimplementations (AddObject, Avoidcrashaddobject);} -(void) Avoidcrashaddobject: (id) anobject { @try {[self avoidcrashaddobject:anobject]; is actually called AddObject}  @catch (nsexception *exception) {//can come here, explaining that the code for adding elements to a mutable array has a problem //you can do the appropriate work here nslog (@ "Exception name:%@ exception Reason:%@", exception .name, Exception.reason);}  @finally {//the code here is bound to execute, you can do the appropriate action}}  @end             

验证上面的代码的确可以捕获异常,并且不会崩溃

    NSString *nilStr = nil;    NSMutableArray *arrayM = [NSMutableArray array];    [arrayM addObject:nilStr];

控制台输出如下


The exception information that was caught. PNG uses category + Runtime + exception capture to write a framework that prevents crashes
    • Use category + Runtime + exception capture to write a framework that prevents crashes

iOS was forgotten by developers in the corner of the nsexception-actually it's very powerful

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.