0

I tried it in objective c, with try catch block.It's working fine with this code

    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);
    }

It's print exception error.

But when I tried it with try catch block in swift, it's not giving exception error and app crashed at that point.

 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
        }

I am trying to handle NSRangeException error in swift 3.

6
  • Why are you hardcoding a possibly out-of-range range? Base your range on the actual length of the data. Avoid the possibility of the error. Code defensively. Commented Feb 26, 2018 at 5:32
  • it's only for a scenario Commented Feb 26, 2018 at 5:36
  • It's a non-catchable programming error to use a bad range in Swift. There's nothing to catch. Write code that only uses a valid range. Commented Feb 26, 2018 at 5:39
  • @rmaddy My answer is same that, how to handle this bacause my data range calculate at run time Commented Feb 26, 2018 at 5:41
  • 1
    One cannot catch NSException in Swift, compare stackoverflow.com/a/24023248/1187415 or stackoverflow.com/q/38737880/1187415 Commented Feb 26, 2018 at 5:53

1 Answer 1

1

At last I reached at following solution that in swift if need to handle range exceptions then we need to do this

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

Total data length(sourceData.length) should be maximum from your staring point(4000) and length of data(20) which you need to retrieve

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

   throw LevelParsingException.InvalidLevelContent
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.