기본적인 예외 던지는 방식
if (str.length > 10) {
throw IllegalStateException("str($str) is too long")
}
Kotlin
복사
•
자바와 거의 유사하지만 new가 불필요
try, catch, finally
fun parse(numberStr: String): Int = try {
Integer.parseInt(numberStr)
} catch (e: Exception) {
throw IOException("일부러 발생시키는 checked exception")
} finally {
println("무조건 실행되는 코드블록")
}
Kotlin
복사
•
try catch finally 구문은 자바와 거의 동일하지만 이 부분도 if나 when과 마찬가지로 식(값으로 취급 가능한 문장)으로 취급
•
java와의 차이점?
◦
checked exception이라고 해도 함수 시그니처에 throws IOException을 붙이지 않아도 됨
◦
java 코드의 경우는 컴파일 오류 발생