Kotlin - Throw Custom Exception

2019-06-14 22:23发布

问题:

How can I throw a custom exception in Kotlin? I didn't really get that much off the docs...

In the docs, it gets described what each exception needs, but how exactly do I implement it?

回答1:

One thing to keep in mind: if you are using the IntelliJ IDE, just a simple copy/paste of Java code can convert it to Kotlin.

Coming to your question, now. If you want to create a custom Exception, just extend Exception class like:

class TestException(message:String): Exception(message)

and throw it like:

throw TestException("Hey, I am testing it")


回答2:

Like this:

Implementation

class CustomException(message: String) : Exception(message)

Usage

 fun main(args: Array<String>) {
     throw CustomException("Error!")            // >>> Exception in thread "main"
 }                                              // >>> CustomException: Error!

For more info: Exceptions