Try-Catch Block不可达? 有一个内部try-finally块导致外部try-catch块无法访问?

我正在尝试在Kotlin中编写简单的网站API调用,但是我在实现try-catch块时遇到了一些麻烦。 直到最后的catch语句将整个块转换成不可达的代码。

// REST web service call to get data from coinmarketcap API inner class RetrieveFeedTask : AsyncTask() { 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 } } } 

我认为最后的catch语句将允许try块被连接,即使它没有连接? 我正在阅读,看到最后的声明将永远运行,所以我认为这可能是问题,但是当我把它转换成一个catch块,它仍然会给我相同的不可达代码。 我想知道这是否仅仅是Kotlin特有的,因为我刚开始学习它。

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") 

它抛出一个exception,因此返回Nothing ,因此将永远是最后执行的东西(如果达到)。

在内部try缺少catch子句意味着任何exception都将被完全忽略。 如果你想在外层try捕获你的exception(尽管finally还包括内层),你可以通过将内层exception添加到内层try来重新抛出内层exception。

 catch (e: Exception) { throw e } 

“TODO”语句使Kotlin无效并使代码无法访问? 看起来我不得不注释掉try块上方的TODO注释,以使其可达。