Language/kotlin

예외 다루기

kimjingyu 2023. 5. 18. 02:36
728x90

try catch finally 구문

// 1. try catch finally 구문 - 주어진 문자열을 정수로 변경
fun parseIntOrThrow(str: String): Int{
    try {
        return str.toInt()
    } catch (e: NumberFormatException) {
        throw IllegalArgumentException("주어진 ${str}는 숫자가 아닙니다.")
    }
}
  • 자바에 비해서 코틀린에서는
    • 기본타입간의 형변환은 .toType()을 사용한다.
    • 타입이 뒤에 위치한다.
    • new를 사용하지 않는다.
    • 포맷팅이 간결하다.
  • 코틀린에서는 try catch 구문 역시 expression이다.
// 주어진 문자열을 정수로 변경 - 실패하면 null 반환
fun parseIntOrNull(str: String): Int? {
    return try {
        str.toInt()
    } catch (e: NumberFormatException) {
        null
    }
}

Checked Exception과 Unchecked Exception

  • 코틀린에서는 Checked Exception과 Unchecked Exception을 구분하지 않는다. -> 모두 Unchecked Exception이다.
fun readFile() {
    val currentFile = File(".")
    val file = File(currentFile.absolutePath + "/file.txt")
    val reader = BufferedReader(FileReader(file))
    println(reader.readLine())
    reader.close()
}

try with resources

  • 코틀린에는 try with resources 구문이 없다.
  • 대신 코틀린의 언어적 특징을 활용해 close를 호출해준다.
  • 대신 use 라는 inlline 확장함수를 사용해야 한다.
fun readFile(path: String) {
    BufferedReader(FileReader(path)).use { reader ->
        println(reader.readLine())
    }
}
728x90