private val handler: CoroutineExceptionHandler = CoroutineExceptionHandler{ _, exception →
println(“Exception thrown in one of the children: $exception”)
}
Can I catch specific exceptions (like with try…catch) for example I want to catch java.net.SocketException. Try…catch around the code doesn’t work and I want to alert the user when server closes the connection.
It’s unlikely try-catch is broken. I’m guessing your try-catch is not actually around the code throwing the exception, but rather around code launching the coroutine that runs the code that throws the exception. Try moving try-catch inside the coroutine that throws the exception.
I have no deep experience with coroutines, but maybe instead of catching exception you simply need to write this:
private val handler = CoroutineExceptionHandler { _, exception ->
when (exception) {
is SocketException -> // handle your exception
else -> throw exception // propagate all other errors
}
}