0


Kotlin异常处理runCatching,getOrNull,onFailure,onSuccess(1)

Kotlin异常处理runCatching,getOrNull,onFailure,onSuccess(1)

  1. fun main(args: Array<String>) {
  2. var s1 = runCatching {
  3. 1 / 1
  4. }.getOrNull()
  5. println(s1) //s1=1,打印1
  6. println("-")
  7. var s2 = runCatching {
  8. 1 / 0 //发生异常
  9. }.getOrNull()
  10. println(s2) //s2为null
  11. println("--")
  12. runCatching {
  13. 1 / 1
  14. }.onFailure {
  15. println("onFailure $it") //不会执行,因为runCatching没有失败
  16. }.onSuccess {
  17. println("onSuccess $it") //执行,因为runCatching成功
  18. }
  19. println("---")
  20. runCatching {
  21. 1 / 0 //发生异常
  22. }.onFailure {
  23. println("onFailure $it") //执行,因为runCatching失敗了
  24. }.onSuccess {
  25. println("onSuccess $it") //不会执行,因为runCatching沒有成功
  26. }
  27. }

1

null

onSuccess 1

onFailure java.lang.ArithmeticException: / by zero

kotlin异常处理try-catch-finally_zhangphil的博客-CSDN博客b-catch: java.lang.RuntimeException: b发生异常。kotlin异常处理try-catch-finally。https://blog.csdn.net/zhangphil/article/details/129800172

标签: kotlin

本文转载自: https://blog.csdn.net/zhangphil/article/details/133279853
版权归原作者 zhangphil 所有, 如有侵权,请联系我们删除。

“Kotlin异常处理runCatching,getOrNull,onFailure,onSuccess(1)”的评论:

还没有评论