【发布时间】:2021-01-15 06:05:18
【问题描述】:
如果抛出异常(如果输入为空或无效),我不想继续代码(打开新活动)。但即使我没有输入所有内容,它也会执行它,就好像什么都没发生一样。错误已被删除,因此它确实捕获了它。
try {
val ip1: String = ip_addr1.text.toString()
val port1: String = port1.text.toString()
val ip2: String = ip_addr2.text.toString()
val port2: String = port2.text.toString()
// Bind to MyService
Intent(this, MyService::class.java).also { intent ->
intent.putExtra("ip1", ip1)
intent.putExtra("port1", port1)
intent.putExtra("ip2", ip2)
intent.putExtra("port2", port2)
bindService(intent, connection, Context.BIND_AUTO_CREATE)
}
val intent = Intent(this, HomeActivity::class.java)
startActivity(intent)
} catch (e: NumberFormatException) {
showToast("Enter IP in Port")
} catch (e: Exception) {
showToast(e.toString())
}
}
【问题讨论】:
-
如果这是在你不想继续的函数中,请将
return放在 catch 块中。 -
也相关。根据 Kotlin 语言设计者的说法,try/catch 是一种代码异味,除非它位于您制作的低级实用程序函数中,因此您不必在一般应用程序代码中使用它。 medium.com/@elizarov/kotlin-and-exceptions-8062f589d07
标签: android sockets kotlin try-catch