kotlin异常机制

Reference

所有的异常类都继承至 Throwable,每个异常包括 message, stack trace 和可选的 cause

依赖于4个关键字 try, catch, finally, throw。

抛出一个异常

throw MyException("Hi There!")

捕获异常

catch 块可以0-n个,finally 块可以省略,但是至少有一个 catch 或者 finally 块。

try {
// some code
}
catch (e: SomeException) {
// handler
}
finally {
// optional finally block
}

try 语句是表达式

fun getUser(uid: Long): User? {
return try {repository.getOne(uid)} catch (e: EntityNotFoundException) {null}
}