Kotlin Exception Handling

Kotlin 예외 처리 (Exception Handling in Kotlin)

예외 처리 기본 (Basic Exception Handling)

Kotlin에서는 예외를 처리하기 위해 try, catch, finally 블록을 사용합니다. try 블록 안에 예외가 발생할 수 있는 코드를 작성하고, catch 블록에서 해당 예외를 처리합니다. finally 블록은 예외 발생 여부와 상관없이 항상 실행됩니다.

기본 예외 처리 예제:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
fun main() {
try {
val result = 10 / 0
} catch (e: ArithmeticException) {
println("ArithmeticException 발생: ${e.message}")
} finally {
println("finally 블록은 항상 실행됩니다.")
}
}
fun main() { try { val result = 10 / 0 } catch (e: ArithmeticException) { println("ArithmeticException 발생: ${e.message}") } finally { println("finally 블록은 항상 실행됩니다.") } }
fun main() {
    try {
        val result = 10 / 0
    } catch (e: ArithmeticException) {
        println("ArithmeticException 발생: ${e.message}")
    } finally {
        println("finally 블록은 항상 실행됩니다.")
    }
}

위 코드에서 0으로 나누기를 시도하면 ArithmeticException이 발생하며, 이 예외는 catch 블록에서 처리됩니다. finally 블록은 항상 실행됩니다.

다중 catch 블록 (Multiple Catch Blocks)

여러 종류의 예외를 처리하기 위해 다중 catch 블록을 사용할 수 있습니다. 각 catch 블록은 다른 유형의 예외를 처리합니다.

다중 catch 블록 예제:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
fun main() {
try {
val numbers = listOf(1, 2, 3)
println(numbers[5])
} catch (e: IndexOutOfBoundsException) {
println("IndexOutOfBoundsException 발생: ${e.message}")
} catch (e: Exception) {
println("Exception 발생: ${e.message}")
} finally {
println("finally 블록은 항상 실행됩니다.")
}
}
fun main() { try { val numbers = listOf(1, 2, 3) println(numbers[5]) } catch (e: IndexOutOfBoundsException) { println("IndexOutOfBoundsException 발생: ${e.message}") } catch (e: Exception) { println("Exception 발생: ${e.message}") } finally { println("finally 블록은 항상 실행됩니다.") } }
fun main() {
    try {
        val numbers = listOf(1, 2, 3)
        println(numbers[5])
    } catch (e: IndexOutOfBoundsException) {
        println("IndexOutOfBoundsException 발생: ${e.message}")
    } catch (e: Exception) {
        println("Exception 발생: ${e.message}")
    } finally {
        println("finally 블록은 항상 실행됩니다.")
    }
}

위 코드에서 잘못된 인덱스 접근으로 IndexOutOfBoundsException이 발생하며, 첫 번째 catch 블록에서 처리됩니다.

사용자 정의 예외 (Custom Exceptions)

Kotlin에서는 사용자 정의 예외를 생성할 수 있습니다. 예외 클래스는 Exception 클래스를 상속받아 정의합니다.

사용자 정의 예외 예제:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
class CustomException(message: String) : Exception(message)
fun main() {
try {
throw CustomException("사용자 정의 예외 발생!")
} catch (e: CustomException) {
println("CustomException 발생: ${e.message}")
} finally {
println("finally 블록은 항상 실행됩니다.")
}
}
class CustomException(message: String) : Exception(message) fun main() { try { throw CustomException("사용자 정의 예외 발생!") } catch (e: CustomException) { println("CustomException 발생: ${e.message}") } finally { println("finally 블록은 항상 실행됩니다.") } }
class CustomException(message: String) : Exception(message)

fun main() {
    try {
        throw CustomException("사용자 정의 예외 발생!")
    } catch (e: CustomException) {
        println("CustomException 발생: ${e.message}")
    } finally {
        println("finally 블록은 항상 실행됩니다.")
    }
}

위 코드에서 CustomException을 던지고 catch 블록에서 이를 처리합니다.

예외 다시 던지기 (Rethrowing Exceptions)

필요한 경우 catch 블록에서 예외를 다시 던질 수 있습니다.

예외 다시 던지기 예제:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
fun main() {
try {
try {
throw ArithmeticException("0으로 나누기 시도!")
} catch (e: ArithmeticException) {
println("ArithmeticException 발생: ${e.message}")
throw e // 예외 다시 던지기
}
} catch (e: ArithmeticException) {
println("다시 잡은 예외: ${e.message}")
}
}
fun main() { try { try { throw ArithmeticException("0으로 나누기 시도!") } catch (e: ArithmeticException) { println("ArithmeticException 발생: ${e.message}") throw e // 예외 다시 던지기 } } catch (e: ArithmeticException) { println("다시 잡은 예외: ${e.message}") } }
fun main() {
    try {
        try {
            throw ArithmeticException("0으로 나누기 시도!")
        } catch (e: ArithmeticException) {
            println("ArithmeticException 발생: ${e.message}")
            throw e  // 예외 다시 던지기
        }
    } catch (e: ArithmeticException) {
        println("다시 잡은 예외: ${e.message}")
    }
}

위 코드에서 내부 try 블록에서 발생한 ArithmeticExceptioncatch 블록에서 다시 던지고, 외부 try 블록에서 다시 잡습니다.

예외를 사용할 수 있는 함수 (Functions with Exceptions)

함수 내에서도 예외 처리를 할 수 있습니다. 예외를 처리하지 않고 함수 밖으로 던질 수도 있습니다.

함수 내 예외 처리 예제:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
fun divide(a: Int, b: Int): Int {
if (b == 0) {
throw ArithmeticException("0으로 나눌 수 없습니다.")
}
return a / b
}
fun main() {
try {
val result = divide(10, 0)
println("결과: $result")
} catch (e: ArithmeticException) {
println("예외 발생: ${e.message}")
}
}
fun divide(a: Int, b: Int): Int { if (b == 0) { throw ArithmeticException("0으로 나눌 수 없습니다.") } return a / b } fun main() { try { val result = divide(10, 0) println("결과: $result") } catch (e: ArithmeticException) { println("예외 발생: ${e.message}") } }
fun divide(a: Int, b: Int): Int {
    if (b == 0) {
        throw ArithmeticException("0으로 나눌 수 없습니다.")
    }
    return a / b
}

fun main() {
    try {
        val result = divide(10, 0)
        println("결과: $result")
    } catch (e: ArithmeticException) {
        println("예외 발생: ${e.message}")
    }
}

위 코드에서 divide 함수는 0으로 나누기를 시도하면 ArithmeticException을 던집니다. 이 예외는 main 함수에서 처리됩니다.

Kotlin의 예외 처리 기능을 이해하고 적절히 사용하면 프로그램의 안정성을 높이고 오류 발생 시 적절한 조치를 취할 수 있습니다.

Leave a Reply

Your email address will not be published. Required fields are marked *