天天看點

Android Kotlin Throws Exception正文自定義異常

轉載請标明出處: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代碼中使用的時候,如下:

Android Kotlin Throws Exception正文自定義異常

會提醒我們報錯,但是如果在 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()
}