TIL

Lec 07. 코틀린에서 예외를 다루는 방법

1. try catch finally 구문

fun parseIntOrThrow(str: String): Int {
  try {
    return str.toInt()
  } catch (e: NumberFormatException) { // 예외 시 예외 발생
    throw IllegalArgumentException("숫자가 아닙니다.")
  }
}
fun parseIntOrThrow(str: String): Int? {
  return try {
    str.toInt()
  } catch (e: NumberFormatException) { // 예외 시 null 반환
    null
  }
}

2. Checked Exception과 Unchecked Exception

3. try with resources

// 자바
public void readFile(String path) throws IOException {
  try (BufferedReader reader = new BufferedReader(new FileReader(path))) {
    System.out.println(reader.readLine());
  }
}
// 코틀린
fun readFile(path: String?) {
    BufferedReader(FileReader(path)).use { reader -> 
        println(reader.readLine()) 
    }
}