如何在目标c中创build自定义exception?

我试图在目标c中实现这样的目标。

@try{ //some code that will raise exception } @catch(CustomException e){//How to create this //catching mechanism } @catch(NSException e){ //Generic catch } 

我需要创buildCustomException类并使用它。 你能帮我创build这个CustomException并指导我如何使用这个。

提前致谢。

在最简单的情况下,我可以使用…声明一个类…

 @interface CustomException : NSException @end @implementation CustomException @end 

…和代码非常像你发布的内容:

  @try{ @throw [[CustomException alloc] initWithName:@"Custom" reason:@"Testing" userInfo:nil]; } @catch(CustomException *ce){ NSLog(@"Caught custom exception"); } @catch(NSException *e){ NSLog(@"Caught generic exception"); } 

Objective-C中的例外情况很less用于控制stream。 我猜你有一个Java(或类似的)背景。

我并不是说你不能写这样的代码,但是对于其他人来看你的代码,如果你没有完全隔离这些exception,那么如果别人使用代码的话也可能会工作的很糟糕。它永远达不到他们的代码。

在Objective-C中通常如何实现

例外情况用于严重错误。 如果预期错误(就好像是因为你想要@try ),你应该尝试并返回一个NSError 。 这是一个遍布于Foundation和Cocoa框架以及第三方框架的devise模式。 在联网,文件读/写或JSON代码( JSONObjectWithData:options:error:寻找示例

你会做什么

你所做的是在你的方法结尾添加一个错误参数(双指针),可能会失败,如下所示:

 - (MyResultObject *)myMethodThatCouldFailWith:(MyObject *)myObject error:(NSError **)error; 

当某人(你或其他人)使用这个方法时如果他们想要传递一个NSError指针,如果发生错误就会被设置,如下所示:

 NSError *error = nil; // Assume no error MyResultObject *result = [self myMethodThatCouldFailWith:myObject error:&error]; if (!result) { // An error occurred, you can check the error object for more information. } 

请注意错误参数之前的&符号( & )。 这意味着你正在发送你的错误点作为参数,这样在有风险的方法里面,指针可以被改变,指向一个新的NSError对象,在方法返回后可以读取它。

现在,在可能失败的方法中,如果发生错误(而不是引发exception),则会将该错误设置为新的NSError对象。 在发生错误时返回nil也很常见,因为这可能意味着计算将无法完成,或者数据不可靠或不相关。

 - (MyResultObject *)myMethodThatCouldFailWith:(MyObject *)myObject error:(NSError **)error { // Do something "risky" ... MyResultObject *result = [MyResultObject somethingRiskyWith:myObject]; // Determine if things went wrong if (!result) { // Set error if a pointer for the error was given if (error != NULL) { *error = [NSError errorWithDomain:yourErrorDomain code:yourErrorCode userInfo:optionalDictionaryOfExtraInfo]; } return nil; } // Everything went fine. return result; } 

现在,如果错误返回,您可以从您指定的错误代码中识别出错误types,您可以在用户信息词典(可以在其中添加大量信息)中阅读更详细的信息。