Android Kotlin Exception处理

转载请标明出处:http://blog.csdn.net/zhaoyanjun6/article/details/118386817
本文出自【赵彦军的博客】

往期精彩文章

Android Coroutines Channels

Android Kotlin协程和Retrofit结合使用

Kotlin实战指南十六:Synchronized、Volatile

Throws Exception

Kotlin 的异常和 Java 的一样, try…catch…finally代码块处理异常,唯一一点不同是:Kotlin 的异常都是 Unchecked exceptions。

checked exceptions 是必须在方法上定义并且处理的异常,比如 Java 的 IoException。

Kotlin 抛出异常是使用 Throws 注解来实现的,如下:

@Throws(IOException::class)
fun createDirectory(file: File) {
    if (file.exists())
        throw IOException("Directory already exists")
    file.createNewFile()
}

当我们在java代码中使用的时候,如下:
在这里插入图片描述
会提醒我们报错,但是如果在 kotlin 文件里使用的时候,就不会有提示。

自定义异常

/**
 * @author : zhaoyanjun
 * @time : 2021/7/5
 * @desc : 自定义异常
 */
class CommonException(code: Int, message: String) : Exception(message)

使用:

@Throws(CommonException::class)
fun createDirectory(file: File) {
    if (file.exists())
        throw CommonException(0, "file is exists")
    file.createNewFile()
}

runCatching


class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        kotlin.runCatching {
            sum(2, 4)
        }.onSuccess {
            Log.d("yy--", "结果正常$it")
        }.onFailure {
            it.printStackTrace()
            Log.d("yy--", "结果异常${it.message}")
        }

    }

    fun sum(num1: Int, num2: Int): Int {
        1 / 0
        return num1 + num2
    }
}

getOrDefault

val result = kotlin.runCatching {
            sum(2, 4)
        }.onSuccess {
            Log.d("yy--", "结果正常$it")
        }.onFailure {
            it.printStackTrace()
            Log.d("yy--", "结果异常${it.message}")
        }.getOrDefault(100)

//如果运行正常,就返回6,运行异常就返回100
Log.d("yy--", "结果$result")

isSuccess、isFailure

val result = kotlin.runCatching {
            sum(2, 4)
        }.onSuccess {
            Log.d("yy--", "结果正常$it")
        }.onFailure {
            it.printStackTrace()
            Log.d("yy--", "结果异常${it.message}")
        }.isFailure

exceptionOrNull

    public fun exceptionOrNull(): Throwable? =
        when (value) {
            is Failure -> value.exception
            else -> null
        }

如果有异常就返回异常,否则返回 Null

getOrNull

    @InlineOnly
    public inline fun getOrNull(): T? =
        when {
            isFailure -> null
            else -> value as T
        }

如果失败了,就返回null ,否则正常返回

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值