gpt4 book ai didi

kotlin - Kotlin : How to invoke super after some computation?

转载 作者:行者123 更新时间:2023-12-03 08:03:29 25 4
gpt4 key购买 nike

目前,我有一个自定义错误,如下所示:

class IsEvenError(message:String):Exception(message)

val n = 10;
if (n%2 == 0) {
throw IsEvenError("${n} is even");
}


问题是,每次我要抛出错误消息时,我都必须手动写出错误消息。

我希望能够将错误消息嵌入类本身,因此我可以执行以下操作:
throw IsEvenError(n); // this should throw an error saying "10 is even".


我该怎么做?

最佳答案

您可以将IsEvenError更改为接受数字而不是字符串,然后将格式化后的字符串传递给Exception:

class IsEvenError(number: Int) : Exception("$number is even")
fun main() : Unit = throw IsEvenError(10)

产生:
Exception in thread "main" IsEvenError: 10 is even
at TestKt.main(Test.kt:2)

关于kotlin - Kotlin : How to invoke super after some computation?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55762820/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com