Kotlin의 예외 처리
Kotlin에서 예외 처리는 프로그램의 안정성과 예측 가능성을 높이는 중요한 기능입니다.
이 가이드에서는 Kotlin의 예외 처리 메커니즘을 상세히 살펴보고, 실제 사용 사례와 함께 이해를 돕겠습니다.
예외의 기본 개념 (Basic Concepts of Exceptions)
Kotlin은 모든 예외를 unchecked로 취급합니다. 이는 예외를 잡을 수 있지만, 명시적으로 처리하거나 선언할 필요가 없다는 의미입니다. 예외 처리는 주로 두 가지 작업으로 구성됩니다:
- 예외 발생(throwing): 문제가 발생했음을 나타냅니다.
- 예외 잡기(catching): 예기치 않은 예외를 수동으로 처리합니다.
예외 발생하기 (Throw Exceptions)
throw
키워드를 사용하여 예외를 수동으로 발생시킬 수 있습니다:
throw IllegalArgumentException()
// 추가 정보 포함
val cause = IllegalStateException("Original cause: illegal state")
if (userInput < 0) {
throw IllegalArgumentException("Input must be non-negative", cause)
}
전제 조건 함수를 사용한 예외 발생 (Throw Exceptions with Precondition Functions)
Kotlin은 require()
, check()
, error()
등의 전제 조건 함수를 제공합니다:
fun getIndices(count: Int): List<Int> {
require(count >= 0) { "Count must be non-negative. You set count to $count." }
return List(count) { it + 1 }
}
fun main() {
println(getIndices(3)) // [1, 2, 3]
// println(getIndices(-1)) // IllegalArgumentException
}
예외 처리하기 (Handle Exceptions)
try-catch
블록을 사용하여 예외를 처리할 수 있습니다:
try {
// 예외가 발생할 수 있는 코드
} catch (e: SomeException) {
// 예외 처리 코드
}
여러 개의 catch
블록을 사용할 수 있으며, 가장 구체적인 예외부터 처리해야 합니다:
open class WithdrawalException(message: String) : Exception(message)
class InsufficientFundsException(message: String) : WithdrawalException(message)
fun processWithdrawal(amount: Double, availableFunds: Double) {
if (amount > availableFunds) {
throw InsufficientFundsException("Insufficient funds for the withdrawal.")
}
if (amount < 1 || amount % 1 != 0.0) {
throw WithdrawalException("Invalid withdrawal amount.")
}
println("Withdrawal processed")
}
fun main() {
val availableFunds = 500.0
val withdrawalAmount = 500.5
try {
processWithdrawal(withdrawalAmount, availableFunds)
} catch (e: InsufficientFundsException) {
println("Caught an InsufficientFundsException: ${e.message}")
} catch (e: WithdrawalException) {
println("Caught a WithdrawalException: ${e.message}")
}
}
finally 블록 (The finally Block)
finally
블록은 예외 발생 여부와 관계없이 항상 실행됩니다:
try {
// 예외가 발생할 수 있는 코드
} catch (e: YourException) {
// 예외 처리
} finally {
// 항상 실행되는 코드
}
커스텀 예외 만들기 (Create Custom Exceptions)
Exception
클래스를 상속받아 커스텀 예외를 만들 수 있습니다:
class MyException: Exception("My message")
open class MyCustomException(message: String): Exception(message)
class SpecificCustomException: MyCustomException("Specific error message")
Nothing 타입 (The Nothing Type)
Nothing
은 Kotlin의 특수한 타입으로, 절대 성공적으로 완료되지 않는 함수나 표현식을 나타냅니다:
fun fail(message: String): Nothing {
throw IllegalArgumentException(message)
}
fun main() {
val s: String = person.name ?: fail("Name required")
println(s) // 이 줄은 실행되지 않습니다.
}
예외 클래스 (Exception Classes)
Kotlin은 다양한 내장 예외 클래스를 제공합니다:
ArithmeticException
IndexOutOfBoundsException
NoSuchElementException
NumberFormatException
NullPointerException
예외 계층 구조 (Exception Hierarchy)
Kotlin의 예외 계층 구조는 Throwable
클래스를 루트로 합니다. Error
와 Exception
은 Throwable
의 직접적인 하위 클래스입니다.
스택 트레이스 (Stack Trace)
스택 트레이스는 예외가 발생한 위치와 호출 순서를 보여주는 디버깅 도구입니다:
throw ArithmeticException("This is an arithmetic exception!")
Kotlin의 예외 처리 메커니즘은 코드의 안정성과 가독성을 크게 향상시킵니다. 예외를 적절히 사용하면 예기치 않은 상황을 효과적으로 처리하고, 더 견고한 애플리케이션을 만들 수 있습니다. 하지만 예외를 과도하게 사용하면 코드의 흐름을 이해하기 어려워질 수 있으므로, 적절한 균형을 유지하는 것이 중요합니다.
Kotlin, 예외처리, try-catch, throw, 커스텀예외, Nothing타입, 스택트레이스, 예외계층구조, 전제조건함수, 안드로이드개발, 서버개발, 코틀린프로그래밍, 에러핸들링, 디버깅, 코드안정성
'개발&프로그래밍' 카테고리의 다른 글
[kotlin] 상속(inheritance) (0) | 2024.08.13 |
---|---|
[kotlin] 클래스 (0) | 2024.08.12 |
[kotlin] Return 과 점프 표현식 (0) | 2024.08.12 |
[Kotlin] 조건문과 반복문 (0) | 2024.08.11 |
[kotlin] 타입 체크와 캐스팅 (0) | 2024.08.11 |
댓글