异常处理帮助Xcode 4.6

时间:2013-06-02 19:07:57

标签: objective-c exception-handling error-handling xcode4.6

你好我是编程新手,但我一直在关注Objective C中的一些教程。我刚刚遇到异常处理教程中的一个问题,好吧,我的代码没有同样的工作方式。

首先,这是我在main中的代码:

#import  < Foundation/Foundation.h> 
#import "Numz.h"

int main(int argc, const char * argv[]){

@autoreleasepool {

    Numz *n = [[Numz alloc]init];
    @try {
        [n thisisgoingtogetanerror] <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< error on this line      
        }

    @catch (NSException *e) {
            NSLog(@"you got an error in your program");
        }
        NSLog(@"this is code aftr the error");
   }

   return 0;
}

上面的错误说

  

'Numz'没有可见的@interface声明选择器   'thisisgoingtogetanerror'

我的界面和实现已创建,但内部没有创建变量或方法,但这不是我首先需要处理错误的原因吗?
此外,我也无法获得任何类型的控制台视图,构建失败并指出我的错误。

可能 xcode 4.6中的一些设置,我需要更改,但我无法运行代码并处理错误。我看过网上找不到任何答案。

任何帮助都会很棒。

2 个答案:

答案 0 :(得分:2)

编译器抱怨,因为你正在调用一个它没有看到永远声明的方法。

将其更改为(假设Numz不是NSArray的子类,也不是count方法):[n count];

请注意,您应该从不使用流控制的异常。也就是说,您不应该@throw异常,然后使用@catch来处理异常并继续执行。 iOS / Cocoa中的例外仅用于表示不可恢复的错误。

试试这个:

@interface NSObject(Badness)
- (void)methodBadness;
@end

然后在代码中调用该方法。编译器不应该警告,运行时应该@throw。

答案 1 :(得分:0)

异常处理用于运行时的错误/异常。但是你得到的错误发生在编译时

您可以通过以下方式导致运行时错误:

@interface RuntimeError : NSObject
+ (void)cause;
@end

@implementation RuntimeError
+ (void)cause {
    NSAssert(NO, @"This is a runtime error caused through a assertion failure")
}
@end

// Call it with
//     [RuntimeError cause]
// inside the @try-Block