kotlin内联函数——runCatching

1.runCatching作用

代替try{}catch{}异常处理,用于捕获异常。

2.runCatching函数介绍

  • 参数:上下文引用对象为参数
  • 返回值:lamda表达式结果

调用runCatching函数,如果调用成功则返回其封装的结果,并可回调onSuccess函数;如果在执行块函数时抛出了任何Throwable异常,则捕获该异常并将其封装为一个失败结果,并回调onFailure函数。例如,

Kotlin 复制代码
var name: String?= null
name.runCatching {
        Log.d(TAG, "runCatching#${this!!.length}")
   }.onSuccess {
        Log.d(TAG, "runCatching#onSuccess:${it.toString()}")
   }.onFailure { 
        Log.d(TAG, "runCatching#onFailure:${it.message}") 
   }
相关推荐
用户0928 分钟前
深入了解 Android 16KB内存页面
android·kotlin
小孔龙29 分钟前
03.Kotlin Serialization - 认识序列化器
kotlin·json
火车叼位1 小时前
Android Studio与命令行Gradle表现不一致问题分析
android
前行的小黑炭3 小时前
【Android】 Context使用不当,存在内存泄漏,语言不生效等等
android·kotlin·app
前行的小黑炭4 小时前
【Android】CoordinatorLayout详解;实现一个交互动画的效果(上滑隐藏,下滑出现);附例子
android·kotlin·app
用户20187928316716 小时前
Android黑夜白天模式切换原理分析
android
芦半山17 小时前
「幽灵调用」背后的真相:一个隐藏多年的Android原生Bug
android
卡尔特斯17 小时前
Android Kotlin 项目代理配置【详细步骤(可选)】
android·java·kotlin
ace望世界17 小时前
安卓的ViewModel
android
ace望世界17 小时前
kotlin的委托
android