Kotlin 异常

作者: jinkui | 来源:发表于2017-05-25 15:14 被阅读793次

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

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

    Kotlin 的异常这么设计,估计是尝试修正 Java 上异常没有达到理论效果。

    Kotlin 异常的使用和 Java 一样:

    val input = Files.newInputStream(path)
    try {
        var byte = input.read()
        //
    } catch (e: IOException) {
        // logcat
    } finally {
        input.close()
    }
    

    方法采用注解的方式抛出异常。

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

    参考
    《Programming Kotlin》Stephen Samuel ,Stefan Bocutiu
    《Kotlin in Action》Dmitry Jemerov,Svetlana Isakova

    相关文章

      网友评论

        本文标题:Kotlin 异常

        本文链接:https://www.haomeiwen.com/subject/qahzxxtx.html