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}") 
   }
相关推荐
alexhilton8 小时前
使用FunctionGemma进行设备端函数调用
android·kotlin·android jetpack
冬奇Lab11 小时前
InputManagerService:输入事件分发与ANR机制
android·源码阅读
张小潇14 小时前
AOSP15 Input专题InputManager源码分析
android·操作系统
lhDream15 小时前
Kotlin 开发者必看!JetBrains 开源 LLM 框架 Koog 快速上手指南(含示例)
kotlin
RdoZam16 小时前
Android-封装基类Activity\Fragment,从0到1记录
android·kotlin
奥陌陌21 小时前
android 打印函数调用堆栈
android
用户9851200358321 小时前
Compose Navigation 3 深度解析(二):基础用法
android·android jetpack
恋猫de小郭1 天前
Android 官方正式官宣 AI 支持 AppFunctions ,Android 官方 MCP 和系统级 OpenClaw 雏形
android·前端·flutter
黄林晴1 天前
Android 17 Beta 2,隐私这把锁又拧紧了
android
Kapaseker1 天前
研究表明,开发者对Kotlin集合的了解不到 20%
android·kotlin