本文已使用 Google Cloud Translation API 自动翻译。
某些文档最好以原文阅读。
异常是在程序执行期间发生的中断正常指令流的事件。 Kotlin 提供了强大的异常处理机制。在本文中,我们将了解如何在 Kotlin 中处理异常。
异常是在程序执行期间发生的中断正常指令流的事件。当异常发生时,程序突然终止。
有两种类型的异常:已检查和未检查。已检查异常是在编译时发生的异常,例如未找到文件时。未经检查的异常是在运行时发生的异常,例如发生被零除错误时。
Kotlin 提供了强大的异常处理机制。 try/catch 块用于处理异常。 try 块包含可能抛出异常的代码。 catch 块包含处理异常的代码。
try {
// code that may throw an exception
} catch (e: Exception) {
// code that handles the exception
}
如果 try 块中发生异常,则执行 catch 块。如果没有异常发生,则跳过 catch 块。
也可以有多个 catch 块来处理不同类型的异常。
try {
// code that may throw an exception
} catch (e: FileNotFoundException) {
// code that handles the FileNotFoundException
} catch (e: IOException) {
// code that handles the IOException
}
finally 块是可选的。无论是否发生异常都会执行。
try {
// code that may throw an exception
} catch (e: Exception) {
// code that handles the exception
} finally {
// code that is always executed
}
可以使用 throw 关键字显式抛出异常。
throw FileNotFoundException()
可以通过扩展 Exception 类来创建自定义异常。
class MyException: Exception() {
}