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}") 
   }
相关推荐
alexhilton13 小时前
端侧RAG实战指南
android·kotlin·android jetpack
二流小码农21 小时前
鸿蒙开发:路由组件升级,支持页面一键创建
android·ios·harmonyos
xq95271 天前
Android 手游SDK组件化开发实战指南
android
煤球王子1 天前
学习记录:Android14中的WiFi-wpa_supplicant(1)
android
张小潇1 天前
AOSP15 Input专题InputDispatcher源码分析
android
TT_Close1 天前
【Flutter×鸿蒙】debug 包也要签名,这点和 Android 差远了
android·flutter·harmonyos
Kapaseker1 天前
2026年,我们还该不该学编程?
android·kotlin
雨白2 天前
Android 快捷方式实战指南:静态、动态与固定快捷方式详解
android
hqk2 天前
鸿蒙项目实战:手把手带你实现 WanAndroid 布局与交互
android·前端·harmonyos
LING2 天前
RN容器启动优化实践
android·react native