面试题答案
一键面试抛出异常
在Objective-C中,可以使用@throw
关键字来抛出异常。异常对象通常是NSException
类或其子类的实例。例如:
NSException *exception = [NSException exceptionWithName:@"CustomException"
reason:@"Some custom error occurred"
userInfo:nil];
@throw exception;
捕获异常
使用@try
、@catch
和@finally
块来捕获和处理异常。@try
块包含可能会抛出异常的代码。@catch
块用于捕获并处理异常,@finally
块中的代码无论是否发生异常都会执行。示例如下:
@try {
// 可能抛出异常的代码
[self someMethodThatMightThrow];
} @catch (NSException *exception) {
NSLog(@"Caught exception: %@, reason: %@", exception.name, exception.reason);
// 处理异常
} @finally {
NSLog(@"This will always be printed");
}
文件读取操作中应用异常机制
假设我们有一个简单的文件读取方法,当文件不存在或无法读取时抛出异常。示例代码如下:
- (NSString *)readFileContents:(NSString *)fileName {
NSString *filePath = [[NSBundle mainBundle] pathForResource:fileName ofType:nil];
if (!filePath) {
NSException *exception = [NSException exceptionWithName:@"FileNotFound"
reason:[NSString stringWithFormat:@"File %@ not found", fileName]
userInfo:nil];
@throw exception;
}
NSError *error;
NSString *fileContents = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:&error];
if (!fileContents) {
NSException *exception = [NSException exceptionWithName:@"FileReadError"
reason:[NSString stringWithFormat:@"Error reading file %@: %@", fileName, error.localizedDescription]
userInfo:nil];
@throw exception;
}
return fileContents;
}
在调用这个方法时,可以捕获可能抛出的异常:
@try {
NSString *contents = [self readFileContents:@"nonexistentFile.txt"];
NSLog(@"File contents: %@", contents);
} @catch (NSException *exception) {
NSLog(@"Caught exception: %@, reason: %@", exception.name, exception.reason);
} @finally {
NSLog(@"File read operation completed.");
}
在实际应用中,异常机制通常用于处理严重错误情况,因为异常处理会带来一定的性能开销,并且Objective-C中异常处理机制与ARC(自动引用计数)有一些复杂的交互,在非严重错误场景下,更常用的是通过NSError来处理错误。