Re-throwing and Exception Chaining
Selectively re-throw exceptions and wrap lower-level errors with cause chaining.
Re-throwing and Wrapping
Sometimes you catch an exception only to log, wrap, or convert it before letting a more specific exception propagate. Kotlin makes this idiomatic.
Plain Re-throw
To re-throw, just throw e again — propagation continues to the next handler.
fun main() {
try {
try { "x".toInt() }
catch (e: NumberFormatException) {
println("logging: ${e.message}")
throw e // re-throw original
}
} catch (e: NumberFormatException) {
println("outer caught: ${e.message}")
}
}All lessons in this course
- try/catch/finally as an Expression
- Creating Custom Exception Classes
- runCatching and Result
- Re-throwing and Exception Chaining