티스토리 뷰

이번 포스팅에서는 코틀린에서 예외를 처리하는 방법에 대해서 알아보자!


1. try catch finally 구문
2. Checked Exception과 Unchecked Exception
3. try with resources 구문


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}는 숫자가 아닙니다.")
    }
}

코틀린에서 기본 타입간의 형변환은 toType()을 사용한다.
또한, 자바에서는 new new IllegalArgumentException이라 했지만, 코틀린에서는 new를 사용하지 않는 것을 확인할 수 있다.


Checked Exception과 Unchecked Exception

프로젝트 내 파일의 내용물을 읽어오는 예제

Java

  public void readFile() throws IOException {
    File currentFile = new File(".");
    File file = new File(currentFile.getAbsolutePath() + "/test.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 + "/test.txt")
    val reader = BufferedReader(FileReader(file))
    println(reader.readLine())
    reader.close()
}

코틀린에서는 Checked ExceptionUnchecked Exception을 구분하지 않는다.
모두 Unchecked Exception이기 때문에, 자바에서처럼 throws를 사용하지 않는다.


try with resources 구문

프로젝트 내 파일의 내용물을 읽어오는 예제

Java

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

Kotlin

fun readFile(path: String) {
    BufferedReader(FileReader(path)).use { reader ->
        println(reader.readLine())
    }
}

코틀린에서는 자바와 다르게 try with resources가 없다. 대신 use라는 inline 확장함수를 사용한다. use에 대한 자세한 내용은 추후 포스팅할 예정이다.


정리

  • 자바와 코틀린 모두 try catch finaly 구문은 문법적으로 완전히 동일하다.
  • Kotlin에서는 try catchexpression이다.
  • Kotlin에서는 모든 예외가 Unchecked Exception이다.
  • Kotlin에서는 try with resources 구문이 없다. 대신, 코틀린의 언어적 특징을 활용해 close를 호출해준다.

'Kotlin' 카테고리의 다른 글

[Kotlin] 클래스  (0) 2022.06.17
[Kotlin] object 키워드  (0) 2022.06.14
[Kotlin] 접근 제한자(Visibility Modifier)  (0) 2022.06.07
[Kotlin] 반복문  (0) 2022.06.01
[Kotlin] null을 대하는 자세  (0) 2022.05.28
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/04   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30
글 보관함