0

I'm using a method that gets JSON data from an API, in Java whenever I use getJSONObject I have to surround the method with a try/catch, since it detects that the method throws a JSONException, I want to be able to force the programmer to surround my function in Kotlin when it's used. The method on which I want to do this is the following:

@Throws(JSONException::class)
    fun parseHitEvents(jsonObject: JSONObject): MutableList<AlgoliaEvent> {
        val hits = jsonObject.optJSONArray("hits")

        val results = ArrayList<AlgoliaEvent>(hits.length()) // Initialize the array list to be of size hits.length

        hits?.forEach<JSONObject> { hit ->
            // Check that each hit is not null
            if (hit == null) return@forEach

            // Parse each hit with a correspond ConciseEvent object
            val event = jsonToObject<ConciseEvent>(hit).apply {
                // We need to get the values from AbstractQuery.LatLng and add them into each event object
                with(hit.getJSONObject("_geoloc")) {
                    _geoloc.lat = getDouble("lat")
                    _geoloc.lng = getDouble("lng")
                }

            // Add the main event in the list of events, so that we can send them as the return value
            results.add(AlgoliaEvent(HitEvent(event)))
        }

        return results
    }

However, when this method is being called in another file, I'm not being forced to surround the method in a try/catch.

Is there a way to do that, or is there a way to implement this kind of logic in a better way?

2 Answers 2

1

In Kotlin, there's no checked exceptions (Source).

No exceptions have to be declared and you aren't forced to catch any exception.

To indicate that an exception can be or has to be catched, you can use the @Throw tag in the documentation

Sign up to request clarification or add additional context in comments.

2 Comments

in the previous method, the @Throwtag is being added, however, the method is not being forced to catch any exceptions
Yes, you can't force it. That's what I said
1

Kotlin does not have checked exceptions. @Throws only forces Java code to check for exceptions and has no effect on Kotlin code.

One alternative is using a sealed class that enables returning either the desired result or an error.

sealed class HitEventsResult {
    data class Success(val value: List<AlgoliaEvent>): HitEventsResult()
    data class Failure(val exception: JSONException): HitEventsResult()
}
fun parseHitEvents(jsonObject: JSONObject): HitEventsResult  {
    try {
        // your original code for getting the results...
        return HitEventsResult.Success(results)
    } catch (e: JSONException){
        return HitEventsResult.Failure(e)
    }
}

Then at the call site:

val hitEventsResult = parseHitEvents(jsonObject)
when (hitEventsResult){
    is Success -> TODO() // do something with result.value
    is Failure -> TODO()
}

or if you want to rethrow:

val hitEventsResult = parseHitEvents(jsonObject)
val hitEvents = when (hitEventsResult) {
    is Success -> result.value
    is Failure -> throw result.exception
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.