面试题答案
一键面试- 关键实现步骤:
- 异常捕获:在Objective - C中,可以使用
@try
、@catch
和@finally
块来捕获异常。@try
块中放置可能会抛出异常的代码,@catch
块用于捕获并处理异常,@finally
块无论是否发生异常都会执行。 - 日志记录:捕获到异常后,将异常信息记录到日志文件中。可以使用
NSLog
先将信息输出到控制台,同时使用NSFileHandle
或NSOutputStream
等类将信息写入文件。
- 异常捕获:在Objective - C中,可以使用
- 涉及的类或方法:
- NSException类:在
@catch
块中,通过捕获NSException
对象来获取异常的详细信息,如异常名称(name
属性)、异常原因(reason
属性)以及异常发生时的调用栈(callStackSymbols
属性)。 - NSFileHandle类:用于文件的读写操作。可以使用
[NSFileHandle fileHandleForWritingAtPath:path]
方法打开一个文件用于写入,如果文件不存在,还需要先创建文件。然后使用writeData:
方法将日志数据写入文件。例如:
- NSException类:在
NSString *logFilePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject] stringByAppendingPathComponent:@"app.log"];
NSFileHandle *fileHandle = [NSFileHandle fileHandleForWritingAtPath:logFilePath];
if (!fileHandle) {
[[NSFileManager defaultManager] createFileAtPath:logFilePath contents:nil attributes:nil];
fileHandle = [NSFileHandle fileHandleForWritingAtPath:logFilePath];
}
NSString *logMessage = [NSString stringWithFormat:@"Exception Name: %@, Reason: %@, Call Stack: %@\n", exception.name, exception.reason, [exception.callStackSymbols componentsJoinedByString:@"\n"]];
NSData *logData = [logMessage dataUsingEncoding:NSUTF8StringEncoding];
[fileHandle seekToEndOfFile];
[fileHandle writeData:logData];
- NSLog方法:虽然
NSLog
主要是将信息输出到控制台,但在开发调试阶段,它有助于快速查看异常信息。例如:
@catch (NSException *exception) {
NSLog(@"Exception caught: %@ - %@", exception.name, exception.reason);
// 记录到文件的操作...
}
示例代码:
@try {
// 可能引发异常的代码,如数组越界访问
NSArray *array = @[@"1", @"2"];
NSString *element = array[10];
} @catch (NSException *exception) {
NSLog(@"Exception caught: %@ - %@", exception.name, exception.reason);
NSString *logFilePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject] stringByAppendingPathComponent:@"app.log"];
NSFileHandle *fileHandle = [NSFileHandle fileHandleForWritingAtPath:logFilePath];
if (!fileHandle) {
[[NSFileManager defaultManager] createFileAtPath:logFilePath contents:nil attributes:nil];
fileHandle = [NSFileHandle fileHandleForWritingAtPath:logFilePath];
}
NSString *logMessage = [NSString stringWithFormat:@"Exception Name: %@, Reason: %@, Call Stack: %@\n", exception.name, exception.reason, [exception.callStackSymbols componentsJoinedByString:@"\n"]];
NSData *logData = [logMessage dataUsingEncoding:NSUTF8StringEncoding];
[fileHandle seekToEndOfFile];
[fileHandle writeData:logData];
} @finally {
// 无论是否发生异常都会执行的代码
}