2010-07-29 12 views
169

Perché il blocco @try non funziona? Arresto anomalo dell'app, ma doveva essere catturato dal blocco @try.@try - blocco catch in Objective-c

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

@try { 
    [test characterAtIndex:6]; 

} 
@catch (NSException * e) { 
    NSLog(@"Exception: %@", e); 
} 
@finally { 
    NSLog(@"finally"); 
} 
+2

È possibile sostituire NSString * test = [NSString stringWithString: @ "ss"]; con NSString * test = @ "ss"; –

risposta

69

Ora ho trovato il problema.

Rimuovere il obj_exception_throw dai miei punti di interruzione risolto questo. Ora è catturato dal blocco @try e anche, NSSetUncaughtExceptionHandler gestirà questo se manca un blocco @try.

+10

Se premi continua quando il debugger si interrompe, dovresti vedere che l'eccezione viene lanciata e catturata dal tuo gestore. – JeremyP

11

Sei sicuro che non è un'altra cosa perché il codice esatto che hai incollato sopra funziona perfettamente.

2010-07-29 16:45:57.677 test[93103:207] Exception: *** -[NSCFString characterAtIndex:]: Range or index out of bounds 
2010-07-29 16:45:57.678 test[93103:207] finally 
104

Tutti funzionano perfettamente :)

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

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

Log:

[__NSCFConstantString characterAtIndex:]: Intervallo o di un indice fuori limite

Char a indice 5 non può essere trovato

L'indice massimo è: 3

+5

Corretto ma un po 'fuorviante - ricorda che il blocco @finally viene eseguito in ENTRAMBI i casi, vale a dire indipendentemente dal fatto che l'eccezione sia stata o non sia stata lanciata. – Elendurwen

+0

Sì, mi manca questo :) – iTux