0

If a method defines a return, but trycatch works and catch a exception, I thought the method will return a nil, but actually it returns the caller. I am curious about what happened indeed in this operation. Here is the code:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    NSString *string = [self testMethod];
    NSLog(@"%@",string);
    return YES;
}

- (NSString *)testMethod {
    @try {
        @throw [NSException exceptionWithName:@"test exception" reason:@"test" userInfo:nil];
        return @"normal return";
    } @catch (NSException *exception) {
        
    } @finally {
        
    }
}

In this situation, I debug the code and found the string is APPDelegate instance.

childrenOurFuture
  • 1,889
  • 2
  • 14
  • 23
  • Because you aren't returning anything in the catch/finally which is where your code should go, it does a implicit `return self`, which could lead to undesired results? I tested and instead I got `null` on a macOS app (not iOS) (which might make more sense) – Larme Jun 11 '21 at 08:10
  • thx a lot, I think returning null is much safer than the caller in many situations. I thought when no returns it will return the caller, but your comment tells me that it not what I thought. If I would like to go deep into it, what direction should I to dig? – childrenOurFuture Jun 11 '21 at 08:29

0 Answers0