JSONItem.Load Generating OutOfBoundsException

I have the following code in my app:

Dim j as New JSONItem
Try
  j.Load(buf)
Catch err as JSONException
  error = True
  error_string = "unable to parse returned data - invalid json"
  Return Nil
End

buf is a string variable containing some JSON data I’ve received from a HTTP download and I use a Try…Catch block to catch any parsing errors.
However, occasionally the app is breaking in the IDE on the j.Load(buf) line flagging an “OutOfBoundsException”!
This doesn’t make sense to me as I’m not accessing any arrays which is where I would expect that error might be generated.

Could there be some bug in the underlying parser code that is generating this and then it’s being caught by the Try block? I’m only intending to catch a JSONException but it seems when this other exception is raised it breaks my code.
The IDE is saying that buf is empty at the time of the error if that makes a difference.

Try this:

dim j as new JSONItem
j.Load "" // Boom

Check to make sure buf is not empty before trying to load it.

Your http request is likely timing out.

The empty string is the problem, but is manifested as OutOfBoundsException instead of JSONException (as Kem demonstrated). Obviously an empty string is not going to give you valid JSON either, so I’d suggest you do variation like this:

Dim j as New JSONItem
Try
  j.Load(buf)
Catch err as JSONException
  error = True
  error_string = "unable to parse returned data - invalid json"
  Return Nil
Catch err as OutOfBoundsException
  error = True
  error_string = "No JSON data available"
  Return Nil
End

Thanks
I’ve put in a check for a null string and now I’ve avoided the issue

I have to say I was not expecting this though, would it not make more sense for any parsing error to generate a JSONException including when the parsed string is null? OutOfBounds seems an inappropriate error to be raised when I normally expect that to be used with errors in accessing arrays.

JSON does support arrays though, so there are times when it’s appropriate.

As Greg notes, JSON does support arrays but I agree in the case of an empty string I would expect it to be JSONException.

But over the years I have learned that when empirical evidence shows a different error is thrown, it is easier to just deal with it too and get on with your life. Either be pre-testing or adding another Catch block. Or be extending JSONItem with another new method such as SafeLoad or whatever. (That is my preferred approach.)