Kotlin 简明教程

Kotlin - Exception Handling

异常处理是编程语言非常重要的一部分。此技术限制了我们的应用程序在运行时生成错误输出。在本章中,我们将学习如何在 Kotlin 中处理运行时异常。Kotlin 中的异常与 Java 中的异常非常相似。所有异常都是“Throwable”类的后代。以下示例展示了如何在 Kotlin 中使用异常处理技术。

Exception handling is a very important part of a programming language. This technique restricts our application from generating the wrong output at runtime. In this chapter, we will learn how to handle runtime exception in Kotlin. The exceptions in Kotlin is pretty similar to the exceptions in Java. All the exceptions are descendants of the “Throwable” class. Following example shows how to use exception handling technique in Kotlin.

fun main(args: Array<String>) {
   try {
      val myVar:Int = 12;
      val v:String = "Tutorialspoint.com";
      v.toInt();
   } catch(e:Exception) {
      e.printStackTrace();
   } finally {
      println("Exception Handeling in Kotlin");
   }
}

在上面的代码片段中,我们声明了一个字符串,然后将其绑定到整数中,这实际上是一个运行时异常。因此,我们将在浏览器中获得以下输出。

In the above piece of code, we have declared a String and later tied that string into the integer, which is actually a runtime exception. Hence, we will get the following output in the browser.

val myVar:Int = 12;
Exception Handeling in Kotlin

Note - 与 Java 一样,Kotlin 也在执行 catch 块后执行 finally 块。

Note − Like Java, Kotlin also executes the finally block after executing the catch block.