【问题标题】:Kotlin try-catch resumes after catchKotlin try-catch 在 catch 后恢复
【发布时间】: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


【解决方案1】:

您已编辑文本并从中获取文本,您没有将其中任何一个转换为数字,因此没有数字格式异常需要捕获。一个空的编辑文本有一个有效的字符串文本为空"",然后你把它放在额外的。

如果你想获得数字值,那么这将触发 try catch

val ip1 = Integer.parseValue(ip_addr1.text.toString())

//same parsing for the others


Intent(this, MyService::class.java).also { intent ->
            intent.putIntExtra("ip1", ip1)
            //same for the others

...

【讨论】:

  • 但在 Kotlin 中,toIntOrNull() 将是首选方式。
  • 我想我希望 IPs 作为字符串,像 127.0.0.1 这样的东西不能用我猜的数字表示。
  • 这不是一个数字,我的答案仍然存在这个问题,为什么要尝试/捕获,如果您使用字符串 @GeoCap 没有什么可捕获的
  • 是的,我想我需要使用除 try/catch 之外的其他东西,感谢您的澄清
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-11-25
  • 2013-09-10
  • 1970-01-01
  • 2020-03-13
  • 2014-04-27
  • 2014-12-18
  • 1970-01-01
相关资源
最近更新 更多