Kotlin 异常处理

来源:互联网 发布:淘宝达人怎么注销 编辑:程序博客网 时间:2024/06/01 10:18

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

原创粉丝点击