I have two questions about exceptions in Kotlin 1....
# getting-started
a
I have two questions about exceptions in Kotlin 1. For sending an exception as a parameter to a function should I use
fun foo(exc: Exception)
or
fun<T : Throwable> foo(exc: KClass<T>)
2. I can't assign a default value for later
fun<T : Throwable> foo(exc: KClass<T> = InvalidParamExc::class)
r
well, passing an instance of exception and passing class are 2 completly different things. I would ask for what reason you want to pass the exception, as the 2 things you shown have different usages
a
When my method is called the client has the option to choose which exception they would like to be thrown when something goes wrong. I want my code to be also interoperable for java users Since Kotlin has both java's throwable and kotlin's throwable it's hard to decide. If you describe the both situations that would be good too
a
I would use the same strategy as java Optional orElseThrow : take a Supplier<Exception> as last argument. In kotlin, that will nicely allow trailing lambda syntax.
☝️ 1
r
I'm not well versed in theme Java interoperability, but isn't
Exception
just typealias of Java's
java.lang.Exception
(in case of Kotlin/JVM ofc) ? Shouldn't just throwing your own subclass of it then be easily interoperable with Java?
but yes, Java's optional is a good example of how a custom exception can work
a
Yep, Kotlin's Exception is an alias (Throwable is not) With Optional it would be something like this if I got you correctly:
Copy code
fun<T : Exception> nonNull(exc: Optional<T>) {
    if (exc.isPresent) throw exc.get()
    else throw CustomExc()
}
r
no, we mean it's
orElseThrow()
method something like this:
Copy code
class CustomException : Exception()

class Test {
    val smthGoesWrong = true

    fun workOrThrow(exceptionSupplier: Supplier<out Exception>? = null) {
        if (smthGoesWrong) {
            throw exceptionSupplier?.get() ?: CustomException()
        }
    }
}

Test().workOrThrow { IllegalArgumentException("") }
1
1
you could also use default argument instead of null, but it's tiny bit unreadable:
Copy code
fun workOrThrow(exceptionSupplier: Supplier<out Exception> = Supplier { CustomException() })
(then you would just need to
throw exceptionSupplier.get()
)
a
Thanks mate, I wasn't familiar with supplier interface
m
@Roukanken maybe extract the default supplier to a constant to make it more readable?
r
could improve it a bit ye
👍 1