Try-Catch Block not reachable? Does having an inner try-finally block cause the outer try-catch block to be unreachable?

时间:2018-01-07 00:19:42

标签: kotlin

I am trying to code a simple website API call in Kotlin, but I am having some trouble implementing a try-catch block. It goes smoothly up until the final catch statement which turns the whole block into unreachable code.

     // REST web service call to get data from coinmarketcap API
inner class RetrieveFeedTask : AsyncTask<Void, Void, String>() {
    override fun doInBackground(vararg p0: Void?): String? {
 //            TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
        try {
            // create a connection
            val siteURL  = URL("https://api.coinmarketcap.com/v1/ticker/?limit=200")
            val urlConn = siteURL.openConnection() as HttpURLConnection
            urlConn.connect()
            // if there the connection is successful
            try {
                // reads the urlConn as a string
                val bufferedReader = urlConn.inputStream.bufferedReader()
                val stringBuilder = StringBuilder("")
                // each line from the json object
                var line : String?
                do {
                    line = bufferedReader.readLine()
                    stringBuilder.append(line).append("\n")
                    if (line === null)
                        break
                } while (true)
                bufferedReader.close()
                return stringBuilder.toString()
            } catch (e : Exception) {
                throw e
            } finally {
                urlConn.disconnect()
            }
        } catch (e : Exception) {
            Log.e("NETWORK","Couldn't connect to the website: " + e)
            return null
        }
    }

    override fun onPostExecute(result: String?) {
        if (result == null) {
            // should return an error message
            testTextView!!.text = "Error with website"
        } else {
            testTextView!!.text = result
        }
    }

}

I thought that the final catch statement would allow the try block to be reached even if it does not connect? I was reading around and saw that the finally statement will always run so I thought that might be the problem, but when I converted that into a catch block, it still would give me the same unreachable code. I was wondering if this was just specific to Kotlin as I am just starting to learn it.

3 个答案:

答案 0 :(得分:1)

TODO将是最后执行的行:

fun x() {
    TODO("Not implemented")
    //following is not reachable
    try {

    } catch (e: Exception) {

    }
}

这是因为TODO的实施:

public inline fun TODO(reason: String): Nothing = 
    throw NotImplementedError("An operation is not implemented: $reason")

它抛出异常并因此返回Nothing,因此将始终是执行的最后一件事(如果到达)。

答案 1 :(得分:0)

内部catch中缺少try子句意味着任何异常都将被完全忽略。如果您想在外部try中捕获异常(同时仍包括内部finally),则可以通过将内部异常添加到内部try来重新抛出内部异常

catch (e: Exception) {
    throw e
}

答案 2 :(得分:0)

对于&#34; TODO&#34;它是Kotlin的东西吗?声明无效并使代码无法访问?似乎我必须在try块上面注释掉TODO注释才能使它可以访问。