Objective C - 从块内部引发的Catch异常

Zol*_*adi 3 objective-c try-catch ios objective-c-blocks

我在app中使用以下代码:

@try {
        if(!self.usernameField.text || [self.usernameField.text isEqualToString:@""])
            [NSException raise:@"Invalid value for username" format:@"Please enter your username."];

        if(!self.passwordField.text || [self.passwordField.text isEqualToString:@""])
            [NSException raise:@"Invalid value for password" format:@"Please enter your password."];


        [LoginManager
         userLogin:self.usernameField.text
         andPassword:self.passwordField.text
         success:^(AFHTTPRequestOperation *op, id response) {

             if([self.delegate respondsToSelector:@selector(loginSuccessWithUserName:)]) {
                 [self.delegate performSelector:@selector(loginSuccessWithUserName:)withObject:self.usernameField.text];
             }

             [self dismissPopoverController];
         }
         failure:^(AFHTTPRequestOperation *op, NSError *err) {
             NSString* nsLocalizedRecoverySuggestion = [err.userInfo objectForKey:@"NSLocalizedRecoverySuggestion"];

             if(err.code == -1009) {

                 [NSException raise:@"No Internet connection" format:@"It appears you’re not connected to the internet, please configure connectivity."];
             }

             if([nsLocalizedRecoverySuggestion rangeOfString:@"Wrong username or password."].location != NSNotFound) {

                 [NSException raise:@"Invalid username or password" format:@"Your given username or password is incorrect"];
             }
             else {
                 [NSException raise:@"BSXLoginViewController" format:@"Error during login"];
             }
         }];
    }
    @catch (NSException *exception) {
        UIAlertView* alert = [[UIAlertView alloc]initWithTitle:@"Login error"
                                                       message:exception.description
                                                      delegate:self
                                             cancelButtonTitle:@"Ok"
                                             otherButtonTitles:nil];
        [alert show];
    }
Run Code Online (Sandbox Code Playgroud)

但是,在故障块中引发的异常不会在catch部分中被捕获.我有点理解为什么它是合乎逻辑的,但我想知道是否有办法告诉块我内部发生的异常应该由我创建的catch部分来处理.

谢谢你的帮助!

真诚的,佐利

gai*_*ige 6

不要这样做.首先,我确信你至少会得到@bbum关于这个的评论,NSException不是在Objective-C中用于可恢复的错误和通过代码传播可恢复的错误(参见Cocoa的异常编程主题简介) .相反,Objective-C中使用的构造NSException基本上用于不可恢复的编程错误,并使用NSError对象来处理可恢复的错误.

但是,你在这里遇到了一个更大的问题,你正在进行的调用会阻止回调,因为它们会在完成之前返回.在这种情况下,在实际抛出异常之前很久就会退出异常处理程序.

在这种情况下,我建议删除异常并failure:通过调度到主队列并在UIAlert那里呈现来处理实际块内部的错误.