본문 바로가기
Java & Kotlin/Kotlin

[Kotlin] 예외를 다루는 방법

by heekng 2022. 7. 6.
반응형

예외를 다루는 방법

try catch finally 구문

Java

private int parseIntOrThrow(@NotNull String str) {
    try {
        return Integer.parseInt(str);
    } catch (NumberFormatException e) {
        throw new IllegalArgumentException(String.format("주어진 %s는 숫자가 아닙니다.", str));
    }
}

Kotlin

fun parseIntOrThrow(str: String): Int {
    try {
        return str.toInt()
    } catch (e: NumberFormatException) {
        throw IllegalArgumentException("주어진 ${str}는 숫자가 아닙니다.")
    }
}

fun parseIntOrThrowV2(str: String): Int? {
    return try {
        str.toInt()
    } catch (e: NumberFormatException) {
        null
    }
}
  • 자바와 코틀린의 try catch 구문은 문법적으로 동일하다.
  • 하지만 코틀린에서 try catch문은 if/else처럼 expression으로 취급되기 때문에 그대로 리턴할 수 있다.

Checked Exception과 Unchecked Exception

Java

public void readFile() throws IOException {
    File currentFile = new File(",");
    File file = new File(currentFile.getAbsolutePath() + "/a.txt");
    BufferedReader reader = new BufferedReader(new FileReader(file));
    System.out.println(reader.readLine());
    reader.close();
}

Kotlin

fun readFile() {
    val currentFile = File(".")
    val file = File(currentFile.absolutePath + "/a.txt")
    val reader = BufferedReader(FileReader(file))
    println(reader.readLine())
    reader.close()
}
  • 코틀린은 자바와 다르게 모든 ExceptionUnchecked Exception이다.
    • 때문에 throws를 볼 일이 없다.

try with resources

Java

public void readFileV2(String path) throws IOException {
    try (BufferedReader reader = new BufferedReader(new FileReader(path))) {
        System.out.println(reader.readLine());
    }
}

Kotlin

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