【问题标题】:Error Handle of NSRangeException in swiftswift中NSRangeException的错误句柄
【发布时间】: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


【解决方案1】:

最后我找到了以下解决方案,如果需要快速处理范围异常,那么我们需要这样做

var sourceString = "This is demo text"
let sourceData = sourceString.data(using: String.Encoding.utf8)!  // sourceData is equivalent to "wav" from question

总数据长度(sourceData.length)应该是您的最大值 您需要检索的起点(4000)和数据长度(20)

guard sourceData.length >= (4000 + 20) else{

   throw LevelParsingException.InvalidLevelContent
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多