Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift Catch Runtime Exceptions

I'm running fuzz testing on an application, and so am looking specifically for runtime errors that aren't handled. The application is written in both ObjC and Swift, but the unit tests are written in Swift.

I understand the basis of swift isn't to catch arbitrary runtime exceptions, but this is purely for unit tests. How do I catch runtime these exceptions (i.e. index out of bounds etc.)

like image 305
Jacob Parker Avatar asked Mar 09 '23 13:03

Jacob Parker


1 Answers

To catch Obj-C exceptions in Swift, I am using a simple Obj-C class:

#import "ObjC2Swift.h"

@implementation ObjC

+ (id)catchException:(id(^)())tryBlock error:(__autoreleasing NSError **)error {
    @try {
        id result = tryBlock();
        return result;
    }
    @catch (NSException *exception) {
        if (error) {
            *error = [[NSError alloc] initWithDomain:exception.name code:0 userInfo:exception.userInfo];
        }
        return nil;
    }
}

@end

In Swift called as

let result = try? ObjC.catchException { ... dangerous code here ... }

You might need a different variant for blocks that don't return anything.

Not to be abused. Obj-C exception are evil and I am using this only because I need a library that uses them.

like image 140
Sulthan Avatar answered Mar 15 '23 13:03

Sulthan