How to catch specific exception in CoroutineExceptionHandler

I have this CoroutineExceptionHandler:

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.

No, you must use try-catch for that.

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
	}
}

You are correct, my mistake. I did read somewhere that in certian cases you can not use try-catch and I think it happened to me, but not in this case.

1 Like