Home > database >  Launch coroutine in try catch block crashes
Launch coroutine in try catch block crashes

Time:01-15

I could not understand the difference between these two functions. Why the func2 crashes program while func1 can caught the exception ?

fun main() {
    runBlocking {
        func1() //Prints exception
        func2() //Program crashes
    }
}

fun CoroutineScope.func1() {
    launch {
        try {
            throw IllegalArgumentException("error")
        } catch (t: Throwable) {
            println(t)
        }
    }
}

fun CoroutineScope.func2() {
    try {
        launch {
            throw IllegalArgumentException("error")
        }
    } catch (t: Throwable) {
        println(t)
    }
}

CodePudding user response:

The code inside "launch" block runs on a separate Coroutine with a different context. The external try/catch cannot catch the exception happening. You need to have try/catch in one block, like your func1.

  •  Tags:  
  • Related