@try - 在Objective-c中捕获块

Ale*_*cus 189 iphone objective-c try-catch-finally nsexception

为什么@try阻止工作?它崩溃了应用程序,但它应该被@try块捕获.

 NSString* test = [NSString stringWithString:@"ss"];

 @try {
    [test characterAtIndex:6];

 }
 @catch (NSException * e) {
    NSLog(@"Exception: %@", e);
 }
 @finally {
    NSLog(@"finally");
 }
Run Code Online (Sandbox Code Playgroud)

iTu*_*Tux 129

一切都完美:)

 NSString *test = @"test";
 unichar a;
 int index = 5;

 @try {
    a = [test characterAtIndex:index];
 }
 @catch (NSException *exception) {
    NSLog(@"%@", exception.reason);
    NSLog(@"Char at index %d cannot be found", index);
    NSLog(@"Max index is: %lu", [test length] - 1);
 }
 @finally {
    NSLog(@"Finally condition");
 }
Run Code Online (Sandbox Code Playgroud)

日志:

[__NSCFConstantString characterAtIndex:]:范围或索引越界

无法找到索引5处的字符

最大指数是:3

最后条件

  • 正确但有点误导 - 记住@finally块在两种情况下都被执行,即无论是否抛出异常. (8认同)

Ale*_*cus 77

现在我发现了问题.

obj_exception_throw从我的断点中删除解决了这个问题.现在它被@try块捕获了,NSSetUncaughtExceptionHandler如果@try块丢失,它将处理它.

  • 如果在调试器中断时你按下继续,你应该看到异常被你的处理程序抛出并捕获. (10认同)