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}") 
   }
相关推荐
西幻凌云1 天前
认识STL序列式容器——List
开发语言·c++·stl·list·序列式容器
~无忧花开~1 天前
JavaScript实现PDF本地预览技巧
开发语言·前端·javascript
靠沿1 天前
Java数据结构初阶——LinkedList
java·开发语言·数据结构
4***99741 天前
Kotlin序列处理
android·开发语言·kotlin
froginwe111 天前
Scala 提取器(Extractor)
开发语言
t***D2641 天前
Kotlin在服务端开发中的生态建设
android·开发语言·kotlin
玲珑Felone1 天前
flutter 状态管理--InheritedWidget、Provider原理解析
android·flutter·ios
BoomHe1 天前
车载应用配置系统签名
android·android studio
Want5951 天前
C/C++跳动的爱心②
c语言·开发语言·c++