如何在Kotlin中丟擲自定義異常?


異常是任何程式語言的重要方面。它可以防止我們的程式碼在執行時生成錯誤的輸出。異常分為兩種型別:

  • 已檢查異常
  • 未檢查異常

已檢查異常

已檢查異常是在編譯時檢查的異常。例如,**FileNotFoundException()** 或 **IOException**。在下面的例子中,我們將看到如何生成一個已檢查異常。

示例

import java.io.File
import java.io.InputStream

fun main(args: Array<String>) {
   try {
      val inputStream: InputStream = File("Hello.txt").inputStream()
   } catch(e:Exception) {
      e.printStackTrace();
   }
}

輸出

執行此程式碼後,結果部分將生成以下輸出。您可以看到,在編譯過程中,我們得到了已檢查異常作為輸出。

java.io.FileNotFoundException: Hello.txt (No such file or directory)
   at java.io.FileInputStream.open0(Native Method)
   at java.io.FileInputStream.open(FileInputStream.java:195)
   at java.io.FileInputStream.<init>(FileInputStream.java:138)
   at MainKt.main(main.kt:6)

未檢查異常

未檢查異常是在編譯時不會檢查的異常;而是在執行時丟擲。例如,我們可以考慮任何 **ArithmeticException, NumberFormatException**。在下面的例子中,我們將看到如何生成一個未檢查異常。

示例

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");
   }
}

輸出

它將產生以下輸出:

Exception Handeling in Kotlin
java.lang.NumberFormatException: For input string: "Tutorialspoint.com"
   at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
   at java.lang.Integer.parseInt(Integer.java:580)
   at java.lang.Integer.parseInt(Integer.java:615)
   at MainKt.main(main.kt:5)

Kotlin中的自定義異常

Kotlin 中的異常概念與 Java 中的非常相似。Kotlin 中的所有異常都是 **Throwable** 類的後代。在 Kotlin 中,開發人員有權建立自己的自定義異常。自定義異常是未檢查異常的一部分,這意味著它們將在執行時丟擲。

自定義異常示例

我們將使用一個非常簡單的示例建立我們自己的自定義異常。在這個示例中,我們宣告一個變數並檢查該變數的值是否小於 50。根據結果,我們將使用 Kotlin 內建功能丟擲自定義異常。

fun main(args: Array<String>) {
   val sampleNumber:Int;
   sampleNumber = 100;

   if(sampleNumber > 50) {
      // throwing custom exception instead of checked Exception
      throw myCustomException("Invalid Input. Enter a correct number")
   } else {
      println("Welcome!! You have entered a correct value")
   }
}

// declaring custom exception class
class myCustomException(message: String) : Exception(message)

輸出

執行此程式碼時,它將產生以下輸出。您可以觀察到我們正在丟擲自定義異常以及傳遞的訊息。

Exception in thread "main" myCustomException: Invalid Input. Enter a correct number
   at MainKt.main(main.kt:7)

更新於:2022年3月1日

310 次瀏覽

啟動您的職業生涯

完成課程獲得認證

開始學習
廣告