Sunstrike
Sunstrike

Reputation: 466

Handle exception both in coroutine handler and try-catch block

If we have for example base handler like

protected val baseHandler = CoroutineExceptionHandler { _, e ->
        handleError(e)
}

And execute our code via try-catch block

scope.launch(baseHandler){
  try{
      throw ...
     }
     catch(e:Exception) {
}

Is it possible to handle exception firstly in catch block and as a fallback in base handler? The goal of this code is to have a base exception handler for all project coroutines.

Upvotes: 2

Views: 199

Answers (1)

zsmb13
zsmb13

Reputation: 89528

The CoroutineExceptionHandler you've created and passed in will be used for exceptions that aren't handled in the coroutine.

For example, if you want to catch one specific type of Exception, and handle all other exceptions in the CoroutineExceptionHandler, you can try-catch for just that type:

GlobalScope.launch(baseHandler) {
    try {
        throw IllegalStateException("oh no it failed")
    } catch (e: IllegalStateException) {
        // Handles the exception
    }
}

If an exception other than IllegalStateException is thrown within the try block, that will be propagated to your handler.

Alternatively, you can catch things in the catch branch, but then re-throw them if you can't handle it there, and want to leave it up to the handler instead:

GlobalScope.launch(baseHandler) {
    try {
        // Code that can throw exceptions
    } catch (e: Exception) {
        if (/* some condition */) {
            throw e
        }
    }
}

Upvotes: 2

Related Questions