【发布时间】:2018-08-05 12:32:23
【问题描述】:
我在目标 c 中使用 try catch 块进行了尝试。这段代码运行良好
NSString *string = @"This is demo text";
NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
//it's(data) length is 17
@try {
NSData *subdata = [data subdataWithRange:NSMakeRange(4000, 20)];
} @catch (NSException *exception) {
NSLog(@"exception ERROR: %@",exception);
}
这是打印异常错误。
但是当我在 swift 中使用 try catch 块尝试它时,它没有给出异常错误并且应用程序在那时崩溃了。
var sourceString = "This is demo text"
let sourceData = sourceString.data(using: String.Encoding.utf8)! // sourceData is equivalent to "wav" from question
guard let subdata = Data(sourceData.subdata(in: 4000 ..< (4000 + 20))) else{
throw LevelParsingException.InvalidLevelContent
}
我正在尝试在 swift 3 中处理 NSRangeException 错误。
【问题讨论】:
-
为什么要硬编码可能超出范围的范围?根据数据的实际长度确定您的范围。避免出错的可能性。防御性代码。
-
只是一个场景
-
在 Swift 中使用错误范围是不可捕获的编程错误。没什么可抓的。编写仅使用有效范围的代码。
-
@rmaddy 我的答案是一样的,如何处理这个问题,因为我的数据范围是在运行时计算的
-
一个不能在 Swift 中捕获 NSException,比较 stackoverflow.com/a/24023248/1187415 或 stackoverflow.com/q/38737880/1187415
标签: ios swift exception-handling try-catch nsdata