728x90
반응형
이번 글에서는 코루틴에서 예외를 처리할 때 launch와 async 코루틴 빌더의 차이를 살펴보려고 한다.
launch 사용 예제
val scope = CoroutineScope(Job())
scope.launch {
delay(100)
throw RuntimeException()
}
Thread.sleep(300)
이 코드를 실행하면 어떤 결과가 나올까?
예외를 처리하는 부분은 없다.
콘솔 창에서 볼 수 있듯 예외가 전파되어 종료되었다.
async 사용 예제
val scope = CoroutineScope(Job())
scope.async {
delay(100)
throw RuntimeException()
}
Thread.sleep(300)
이번에는 단순히 launch를 async로 바꿔보았다.
실행 결과는 과연 같을까?
결과는 문제없이 실행이 종료된다.
물론 structured concurrency 컨셉에 의해 부모가 일반 Job이기 때문에
왜 그럴까?
async는 Deferred 객체 형태로 결과를 리턴한다.
따라서, async로 시작된 코루틴이 실패하게 되면 그 예외는 Deferred 객체 안에 캡슐화되고
await를 호출해 실제 결과를 받을 때만 예외가 던져진다(throw).
async 예제 예외발생시켜보기
이제는 async 빌더를 사용한 예외를 발생시켜보자.
val exceptionHandler = CoroutineExceptionHandler { coroutineContext, throwable ->
println("Exception catched in Handler")
}
val scope = CoroutineScope(Job() + exceptionHandler)
val deferred = scope.async {
delay(100)
throw RuntimeException()
}
scope.launch {
deferred.await()
}
Thread.sleep(300)
이제 이 코드를 실행해보면 실제로 예외가 발생할 것이다.
하지만 이 코드블럭은 launch 빌더로 실행한 것과 달리
앱의 크래시는 발생하지 않는데 ExceptionHandler로 예외를 처리했기 때문이다.
728x90
반응형
'Study > Kotlin' 카테고리의 다른 글
Coroutines try-catch vs ExceptionHandler (0) | 2025.07.23 |
---|---|
Exception Handling Using ExceptionHandler in Coroutines (0) | 2025.05.30 |
Exception Handling Using try-catch Clause in Coroutines (0) | 2025.05.06 |
NonCancellable Coroutines 사용해보기 (0) | 2025.04.07 |
Coroutines Cooperative Cancellation (0) | 2025.04.06 |