Kotlin 中丟擲自定義異常
異常是任何程式語言的重要方面。它可以防止我們的程式碼在執行時生成不正確的輸出。
Kotlin 中的異常概念與 Java 中的異常概念非常相似。Kotlin 中的所有異常都是 **Throwable** 類的後代。在 Kotlin 中,開發人員有權建立自己的自定義異常。
自定義異常是 **未檢查異常** 的一部分,這意味著它們將在執行時丟擲。
在深入瞭解 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(); } }
輸出
執行以上程式碼段後,它將生成以下輸出。您可以看到,在編譯時,我們得到了檢查異常作為輸出。
$kotlinc -nowarn main.kt -include-runtime -d main.jar $java -Xmx128M -Xms16M -jar main.jar 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.(FileInputStream.java:138) at MainKt.main(main.kt:6)
未檢查異常
未檢查異常是在編譯時不檢查的異常;而是會在執行時丟擲。在下面的示例中,我們將生成一個未檢查異常。我們可以將 ArithmeticException、NumberFormatException 視為未檢查異常的示例。
示例
fun main(args: Array) { try { val myVar:Int = 12; val v:String = "Tutorialspoint.com"; v.toInt(); } catch(e:Exception) { e.printStackTrace(); } finally { println("Exception Handeling in Kotlin"); } }
輸出
執行以上程式碼段後,它將產生以下輸出 -
$kotlinc -nowarn main.kt -include-runtime -d main.jar $java -Xmx128M -Xms16M -jar main.jar Exception Handeling in Kotlin java.lang.NumberFormatException: For input string: "Tutorialspoint.com" at java.lang.NumberFormatException.forInputString(NumberFormatExc eption.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 中的自定義異常
我們將使用一個非常簡單的示例來建立我們自己的自定義異常。在此示例中,我們宣告一個變數並檢查該變數的值是否小於 50。根據結果,我們將使用 Kotlin 內建功能丟擲自定義異常。
示例
fun main(args: Array) { val sampleNumber:Int; sampleNumber = 100; if(sampleNumber > 50) { //throwing custom exception instead of other checked Exception throw myCustomException("Invalid Inputs - Please enter a correct number") } else { println("Welcome !! you have entered a correct value") } } //declaring custom exception class class myCustomException(message: String) : Exception(message)
輸出
當我們執行此程式碼時,它將產生以下輸出。您可以觀察到我們正在丟擲我們的自定義異常以及傳遞的訊息。
$kotlinc -nowarn main.kt -include-runtime -d main.jar $java -Xmx128M -Xms16M -jar main.jar Exception in thread "main" myCustomException: Invalid Inputs - Please enter a correct number at MainKt.main(main.kt:7)
廣告