728x90
반응형
이번에는 CoroutineExceptionHandler로 예외 처리를 해보도록 하자.
기존 try-catch 구문과는 어떤 차이가 있는지도 볼 예정이다.
처리할 코드
val scope = CoroutineScope(Job())
scope.launch {
throw RuntimeException()
}
Thread.sleep(1000)
CoroutineExceptionHandler 사용 지점
이 핸들러는 Coroutine의 Context 요소이다.
이전 글에서의 기억을 떠올려본다면 가장 대표적인 Context 요소는 Dispatcher일 것이다.
또한, '+' 연산자를 사용하면 여러 Context 요소를 사용할 수 있다.
그럼 위 코드에서 어떤 위치에 핸들러를 주입해야할까?
정답은 두 위치에서 가능한데, 하나는 Job()에 '+' 연산자를 사용하는 방법이 있고, launch에 사용하는 방법이 있다.
(해당 이유는 아래에서 더 설명해보도록 하겠다)
코드로 확인해보기
val exceptionHandler = CoroutineExceptionHandler { coroutineContext, throwable ->
println("Caught $throwable}"}
}
// 첫번째 방법
val scope = CoroutineScope(Job() + exceptionHandler)
// 두번째 방법
scope.launch(exceptionHandler) {
throw RuntimeException()
}
Thread.sleep(1000)
첫번째와 두번째 방법을 통해 핸들러를 주입한 결과, 출력물은 동일하다.
주의할 점
핸들러는 Coroutine Scope Context 내 혹은 Top-level Coroutine에만 설치할 수 있다.
여기서 Top-level Coroutine이란 코루틴 스코프에서 직접 시작되었거나 SupervisorJob의 직접적인 자식인 코루틴을 의미한다.
또한 핸들러는 중첩된 코루틴이나 자식 코루틴에 설치하는 경우 효과가 없다.
아래 코드 블럭처럼 말이다.
scope.launch {
launch(exceptionHandler) {
throw RuntimeException()
}
}
728x90
반응형
'Study > Kotlin' 카테고리의 다른 글
Coroutines try-catch vs ExceptionHandler (0) | 2025.07.23 |
---|---|
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 |
LifecycleScope 간단히 알아보기 (0) | 2025.02.26 |