I have two questions about exceptions in Kotlin 1....
# getting-started
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)
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)
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
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
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
I'm not well versed in theme Java interoperability, but isn't
just typealias of Java's
(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
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()
no, we mean it's
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("") }
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()
Thanks mate, I wasn't familiar with supplier interface
@Roukanken maybe extract the default supplier to a constant to make it more readable?
could improve it a bit ye
👍 1