当前位置 : 主页 > 手机开发 > ios >

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

来源:互联网 收集:自由互联 发布时间:2021-06-11
我在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 || [
我在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];
    }

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

谢谢你的帮助!

此致
佐利

不要这样做.首先,我确信你至少会得到@bbum关于这一点的评论,NSException不是在Objective-C中用于可恢复的错误,而是通过代码传播可恢复的错误(参见 Introduction to Exception Programming Topics for Cocoa).相反,Objective-C中使用的构造基本上是针对不可恢复的编程错误使用NSException,并使用NSError对象来处理可恢复的错误.

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

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

网友评论