cha*_*l03 50
需要记住的一件事是:如果您使用的是IntelliJ IDE,只需简单地复制/粘贴Java代码即可将其转换为Kotlin.
现在来看你的问题.如果要创建自定义Exception,只需扩展Exception类,如:
class TestException(message:String): Exception(message)
Run Code Online (Sandbox Code Playgroud)
扔它像:
throw TestException("Hey, I am testing it")
Run Code Online (Sandbox Code Playgroud)
Dow*_*zza 42
大多数这些答案只是忽略了 Exception 有 4 个构造函数的事实。如果您希望能够在正常异常工作的所有情况下使用它,请执行以下操作:
class CustomException : Exception {
constructor() : super()
constructor(message: String) : super(message)
constructor(message: String, cause: Throwable) : super(message, cause)
constructor(cause: Throwable) : super(cause)
}
Run Code Online (Sandbox Code Playgroud)
这会覆盖所有 4 个构造函数并只传递参数。
小智 38
我知道这已经很旧了,但我想详细说明@DownloadPizza 的答案:/sf/answers/4537282781/
您实际上不需要四个构造函数。您只需要两个来匹配基本 Exception 类的四个:
class CustomException(message: String? = null, cause: Throwable? = null) : Exception(message, cause) {
constructor(cause: Throwable) : this(null, cause)
}
Run Code Online (Sandbox Code Playgroud)
Exception 基类来自 Java 标准库,并且 Java 没有默认参数,因此 Java 类必须为每种可接受的输入组合提供四个构造函数。此外,message和 都cause允许出现null在 Exception 中,所以如果我们试图与 Exception 100% 兼容,我们的也应该是这样。
我们需要第二个构造函数的唯一原因是避免在 Kotlin 代码中使用命名参数语法:CustomException(cause = fooThrowable)vs Exception(fooThrowable)。
Ale*_*nov 10
像这样:
class CustomException(message: String) : Exception(message)
Run Code Online (Sandbox Code Playgroud)
有关更多信息:例外