美文网首页
iOS中的异常处理

iOS中的异常处理

作者: DevWin | 来源:发表于2018-01-13 11:58 被阅读0次
- (void)viewDidLoad {
    [super viewDidLoad];
    @try{
//try里面放可能会抛出异常的代码
        [self test:10 num2:0];
    }@catch(CustomException *e){
//只能在一个catch里面捕获到异常,如果异常是CustomException对象,那么就会在此捕获到异常
        NSLog(@"捕获到CustomException异常:%@",e);
    }@catch(NSException *e){
//只能在一个catch里面捕获到异常,如果异常是不是CustomException对象,那么就会在此捕获到异常
        NSLog(@"最终捕获到NSException:%@",e);
    }@finally{
        NSLog(@"不管有没有捕获到异常,finally最终都会调用");
    }
    /*跟java中一样,代码同时只可能出现一种异常,不可能同时出现多个异常.
     如果出现第一个异常类型就进入第一个catch,如出现第二个异常类型就进入第二个catch.不可能同时进入两个catch
     */
    
    @try{
        [self test2:10 num2:0];
    }@catch(NSException *e){
        NSLog(@"________%@",e);
    }
    
    @try{
        [self test3:5 num2:0];
    }@catch(CustomException *e){
        NSLog(@"++++++++%@",e);
    }
    
    @try{
        [self test4:6 num2:0];
    }@catch(NSException *e){
        NSLog(@"**********%@",e);
    }
}

//抛异常的方式一:@throw NSException对象
- (void)test:(int)num1 num2:(int)num2 {
    if(num2 == 0){
        //抛异常
        //如果执行到下面这句,那么后面的代码就不会执行了
        @throw [[CustomException alloc] initWithName:@"exceptionError" reason:@"除数不能为0" userInfo:nil];
        //抛出异常,后面的代码就不会执行了,相等于return一个错误
    }
    int c = num1/num2;
    NSLog(@"%d",c);
}

//抛异常的方式二: NSAssert
- (void)test2:(int)num1 num2:(int)num2 {
    //NSAssert的异常也能被捕获
    NSAssert(num2 != 0, @"除数不能为零");
    int c = num1/num2;
    NSLog(@"%d",c);
}

//抛异常的方式三:创建NSException对象 然后调用raise方法
- (void)test3:(int)num1 num2:(int)num2 {
    if(num2 == 0){
      //抛异常
      //自定义异常
        CustomException *e = [[CustomException alloc] initWithName:@"exceptionError" reason:@"除数不能为0" userInfo:nil];
        //如果执行到下面这句,那么后面的代码就不会执行了
        [e raise];
    }
    int c = num1/num2;
    NSLog(@"%d",c);
}

//抛异常的方式四:直接通过raise方法创建NSException对象
- (void)test4:(int)num1 num2:(int)num2 {
    if(num2 == 0){
        //抛异常
        //如果执行到下面这句,那么后面的代码就不会执行了
        [NSException raise:@"发生异常了" format:@"%@",@"num2不能为0"];
    }
    int c = num1/num2;
    NSLog(@"%d",c);
}

相关文章

网友评论

      本文标题:iOS中的异常处理

      本文链接:https://www.haomeiwen.com/subject/cmlcoxtx.html