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}") 
   }
相关推荐
阿巴斯甜21 小时前
Android 报错:Zip file '/Users/lyy/develop/repoAndroidLapp/l-app-android-ble/app/bu
android
Kapaseker1 天前
实战 Compose 中的 IntrinsicSize
android·kotlin
xq95271 天前
Andorid Google 登录接入文档
android
黄林晴1 天前
告别 Modifier 地狱,Compose 样式系统要变天了
android·android jetpack
冬奇Lab2 天前
Android触摸事件分发、手势识别与输入优化实战
android·源码阅读
城东米粉儿2 天前
Android MediaPlayer 笔记
android
Jony_2 天前
Android 启动优化方案
android
阿巴斯甜2 天前
Android studio 报错:Cause: error=86, Bad CPU type in executable
android
张小潇2 天前
AOSP15 Input专题InputReader源码分析
android
_小马快跑_2 天前
Kotlin | 协程调度器选择:何时用CoroutineScope配置,何时用launch指定?
android