Kotlin没有错误警告并处理了它的异常

问题描述 投票:0回答:1

[我正在使用一种从API获取JSON数据的方法,在Java中,每当我使用getJSONObject时,都必须用try / catch包围该方法,因为它检测到该方法抛出了JSONException,所以我想以便迫使程序员在使用Kotlin时围绕我的功能。我要执行此操作的方法如下:

@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
    }

但是,当在另一个文件中调用此方法时,不会被强制在try / catch中包围该方法。

有没有办法做到这一点,或者有没有办法更好地实现这种逻辑?

android exception kotlin handle
1个回答
0
投票

在Kotlin中,没有检查的异常(Source)。

© www.soinside.com 2019 - 2024. All rights reserved.