如何在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)
广告
数据结构
网络
关系数据库管理系统(RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP