协程异常处理自测题,答案在评论区。
1. child1、child2 的父 Job 是谁?child2 能执行完成吗?
val scope = CoroutineScope(Job())
val job = scope.launch(SupervisorJob()) {
launch { // Child 1
throw IllegalArgumentException()
}
launch { // Child 2
delay(1000)
println("child 2 run over")
}
}
2. 异常能被捕获吗?coroutineScope 换成 supervisorScope 呢?
try {
coroutineScope {
launch {
// Child 1
throw IllegalArgumentException()
}
launch {
// Child 2
delay(1000)
println("child 2 run over")
}
}
} catch (t: Throwable) {
println("catch t")
}
3. 异常能被捕获吗?
try {
supervisorScope {
throw RuntimeException()
}
} catch (t: Throwable) {
// Handle exception
}
4. Child 2 能执行完成吗?
GlobalScope.launch {
throw RuntimeException("")
}
GlobalScope.launch {
// Child 2
delay(100)
println("child2 over")
}
5. 异常会在哪里被捕获?为什么?
CoroutineScope(Job() + CoroutineExceptionHandler { coroutineContext, throwable ->
println("catch ex in scope")
}).launch(CoroutineExceptionHandler { coroutineContext, throwable ->
println("catch ex in top Coroutine")
}) {
throw RuntimeException()
}
6. runBlocking 中 CoroutineExceptionHandler 能捕获异常吗?
runBlocking(CoroutineExceptionHandler { coroutineContext, throwable ->
println("catch ex in CoroutineExceptionHandler")
}) {
throw Exception() //抛出异常
}
7. async抛出的异常能被捕获吗?为什么?
supervisorScope {
try {
val deferred = async { throw Exception() } //抛出异常
deferred.await()
} catch (t: Throwable) {
println("catch ex in catch block")
}
}
supervisorScope {
val deferred = async(CoroutineExceptionHandler { coroutineContext, throwable ->
println("catch ex in async CoroutineExceptionHandler")
}) { throw Exception() } //抛出异常
deferred.await()
}
coroutineScope {
try {
val deferred = async { throw Exception() } //抛出异常
deferred.await()
} catch (t: Throwable) {
println("catch ex in catch block")
}
}
8. 谁捕获了异常
CoroutineScope(Job()).launch {
val deferred = async(SupervisorJob() + CoroutineExceptionHandler { _, _ ->
println("捕获异常") //1
}) {
throw Exception()
}
try {
deferred.await() //抛出异常
} catch (t: Throwable) {
println("捕获异常") //2
}
}.join()