Exception Handling Using ExceptionHandler in Coroutines

2025. 5. 30. 18:30·Study/Kotlin
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
'Study/Kotlin' 카테고리의 다른 글
  • Coroutines try-catch vs ExceptionHandler
  • Exception Handling Using try-catch Clause in Coroutines
  • NonCancellable Coroutines 사용해보기
  • Coroutines Cooperative Cancellation
BonusTrack02.dev
BonusTrack02.dev
공부, 일상
  • BonusTrack02.dev
    BonusTrack02.dev
    BonusTrack02.dev
  • 전체
    오늘
    어제
    • 분류 전체보기 (239)
      • Dev experience (87)
        • Android (86)
        • Kotlin (1)
      • Study (63)
        • Kotlin (27)
        • Swift (17)
        • Java (19)
      • 프로그래머스 (68)
      • 주저리주저리 (21)
        • 카페 (5)
        • 음식점 (4)
        • 컨퍼런스 (1)
        • 팝업스토어 (4)
        • 전시회 (1)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    getNumericValue
    CodeLab
    room
    코루틴
    프로그래머스
    Java
    ViewModel
    ios
    Material
    android
    스위프트
    안드로이드
    aac
    coroutines
    daterangepicker
    PCCE
    배열
    jetpack
    자바
    코틀린
    Observer
    오블완
    MVVM
    Kotlin
    programmers
    viewModelScope
    LiveData
    SWIFT
    티스토리챌린지
    databinding
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
BonusTrack02.dev
Exception Handling Using ExceptionHandler in Coroutines
상단으로

티스토리툴바