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.

Yatendra
  • 1,310
  • 1
  • 18
  • 31
  • 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. – rmaddy Feb 26 '18 at 05:32
  • it's only for a scenario – Yatendra Feb 26 '18 at 05: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. – rmaddy Feb 26 '18 at 05:39
  • @rmaddy My answer is same that, how to handle this bacause my data range calculate at run time – Yatendra Feb 26 '18 at 05:41
  • I already told you what you need to do. Instead of hardcoding vastly out-of-range values, calculate valid range values based on the actual size of the data. – rmaddy Feb 26 '18 at 05:45
  • 1
    One *cannot* catch NSException in Swift, compare https://stackoverflow.com/a/24023248/1187415 or https://stackoverflow.com/q/38737880/1187415 – Martin R Feb 26 '18 at 05:53

1 Answers1

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
}
Yatendra
  • 1,310
  • 1
  • 18
  • 31