KOTLIN · 비동기
예외 전파 (Exception Propagation)
코루틴의 예외 전파 메커니즘을 이해합니다. launch와 async의 예외 처리 차이를 다룹니다.
비동기고급exceptioncoroutineExceptionHandlersupervisorScopepropagation
핵심 설명
코루틴의 예외 전파 메커니즘을 이해합니다. launch와 async의 예외 처리 차이를 다룹니다.
Kotlin code
import kotlinx.coroutines.*
fun main() = runBlocking {
// CoroutineExceptionHandler
val handler = CoroutineExceptionHandler { _, e ->
println("핸들러: ${e.message}")
}
// launch: 예외가 즉시 전파
val scope = CoroutineScope(SupervisorJob() + handler)
scope.launch {
throw RuntimeException("launch 예외")
}
delay(100)
// async: await() 호출 시 예외 전파
val deferred = scope.async {
throw RuntimeException("async 예외")
}
try {
deferred.await()
} catch (e: Exception) {
println("await 캐치: ${e.message}")
}
// supervisorScope 내 개별 처리
supervisorScope {
val child1 = launch {
throw RuntimeException("자식1 실패")
}
val child2 = launch {
delay(100)
println("자식2 정상 실행")
}
child1.join()
child2.join()
}
}학습 팁
CoroutineExceptionHandler는 launch에서만 동작합니다. async의 예외는 await() 호출부에서 try-catch로 처리합니다.
주의할 점
coroutineScope 내에서 자식이 실패하면 모든 형제도 취소됩니다. 독립적인 실패 처리가 필요하면 supervisorScope를 사용하세요.
자주 묻는 질문
예외 전파 (Exception Propagation)란 무엇인가요?
코루틴의 예외 전파 메커니즘을 이해합니다. launch 와 async 의 예외 처리 차이를 다룹니다.
예외 전파 (Exception Propagation) 학습 시 주의할 점은 무엇인가요?
coroutineScope 내에서 자식이 실패하면 모든 형제도 취소됩니다. 독립적인 실패 처리가 필요하면 supervisorScope 를 사용하세요.
Continue Learning
Kotlin 학습을 이어가세요
총 200개의 독립 HTML 학습 문서 중 하나입니다. 각 문서는 고유 URL과 canonical 메타데이터를 가집니다.