try-catch
자체는 자바와 유사하다.Int
로 형변환하는 예제fun parseIntOrThrow(str: String): Int {
try {
return str.toInt()
} catch (e: NumberFormatException) { // 예외 시 예외 발생
throw IllegalArgumentException("숫자가 아닙니다.")
}
}
try-catch
자체가 Expression이기 대문에 바로 return
할 수도 있다.fun parseIntOrThrow(str: String): Int? {
return try {
str.toInt()
} catch (e: NumberFormatException) { // 예외 시 null 반환
null
}
}
IOException
등은 Checked Exception이기 때문에 throw
하는 등의 처리가 필요하다.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())
}
}
BufferedReader
의 확장함수 use
를 활용하여 작성할 수 있다.close
를 호출해준다.