toffor
toffor

Reputation: 1299

Launch coroutine in try catch block crashes

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

Upvotes: 1

Views: 806

Answers (1)

Harry
Harry

Reputation: 386

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.

Upvotes: 4

Related Questions