Difference between using `invokeOnCompletion` and `try-catch`

Viewed 626

As the title implies, I am curious if there's any difference between doing this;

fun main() {
  val job = GlobalScope.launch(Dispatchers.Main) {
      withTimeout(2000L) {
        delayMe()
      }
  }
  job.invokeOnCompletion { cause -> println("We were canceled due to $cause") }
}

suspend fun delayMe() {
  withContext(Dispatchers.Default) {
    delay(5000L)
  }
}

or this;

fun main() {
  GlobalScope.launch(Dispatchers.Main) {
    try {
      withTimeout(2000L) {
        delayMe()
      }
    } catch(cause: Exception){
        println("We were canceled due to $cause")
    }
  }
  ...
}

...

in terms of handling exceptions inside coroutines.

PS: The sample code above is inspired from here.

0 Answers
Related