转载请标明出处:http://blog.csdn.net/zhaoyanjun6/article/details/118386817
本文出自【赵彦军的博客】
往期精彩文章
Android Coroutines Channels
Android Kotlin协程和Retrofit结合使用
Kotlin实战指南十六:Synchronized、Volatile
文章目录
- 正文
- 自定义异常
正文
Kotlin 的异常和 Java 的一样, try…catch…finally代码块处理异常,唯一一点不同是:Kotlin 的异常都是 Unchecked exceptions。
checked exceptions 是必须在方法上定义并且处理的异常,比如 Java 的 IoException。
@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()
}