Welcome! Everything is fine.

[Kotlin] 7강. 코틀린에서 예외를 다루는 방법 본문

Kotlin

[Kotlin] 7강. 코틀린에서 예외를 다루는 방법

개발곰발 2023. 12. 9.
728x90

* 인프런 강의 - 자바 개발자를 위한 코틀린 입문(Java to Kotlin Starter Guide)을 듣고 정리한 내용입니다.

 

🔗 6강 내용

 

[Kotlin] 6강. 코틀린에서 반복문을 다루는 방법

* 인프런 강의 - 자바 개발자를 위한 코틀린 입문(Java to Kotlin Starter Guide)을 듣고 정리한 내용입니다. 🔗 5강 내용 [Kotlin] 5강. 코틀린에서 조건문을 다루는 방법 * 인프런 강의 - 자바 개발자를 위

3uomlkh.tistory.com

7강. 코틀린에서 예외를 다루는 방법

try catch finally 구문

코틀린에서 try catch finally의 문법은 자바와 동일하다고 볼 수 있다.

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

 

아래와 같이 몇 가지 다른점이 있는데, 지금까지 공부했던 내용이다.

  • 기본타입간의 형변환은 toType()을 사용한다.
  • 타입이 뒤에 위치한다.
  • new를 사용하지 않는다.
  • 포맷팅이 간결하다.

또한 코틀린에서는 if-else처럼 try-catch도 하나의 Expression으로 간주한다. 아래 예시를 보자!

다음과 같은 코드는..

fun parseIntOrThrow(str: String): Int? {
  try {
    return str.toInt()
  } catch (e: NumberFormatException) {
    return null
  }
}

이렇게 수정해서 return을 한 번만 쓸 수 있다.

fun parseIntOrThrow(str: String): Int? {
  return try {
    str.toInt()
  } catch (e: NumberFormatException) {
    null
  }
}

Checked Exception과 Unchecked Exception

코틀린에서는 Checked Exception과 Unchecked Exception을 구분하지 않는다. 모두 Unchecked Exception이다.

try with resources

자바에서 try with resources 구문 이란 다음과 같이 try 안에 외부 자원을 만들어주고 try가 끝나면 자동으로 외부 자원을 닫아주는 구문이다.

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

코틀린에서는 try with resources 구문이 없고, 대신 use라는 inline 확장함수를 사용해야 한다.

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