발생한 예외를 함수 호출 단에서 처리하지 않으면 함수 호출 스택을 거슬러 올라가면서 예외를 처리하는 부분이 나올 때까지 예외를 다시 던진다.
코틀린의 throw는 식이므로 다른 식에 포함될 수 있다.
fun main() {
val res = check(101)
println(res)
}
fun check(number: Int): String {
val percentage = if (number in 0..100)
"$number%"
else
throw IllegalArgumentException()
return percentage
}
Java와 달리 Kotlin은 함수가 던질 수 있는 예외를 명시할 필요가 없다.
체크 예외(checked Exception) : 컴파일러가 예외 처리를 했는지 확인하는 Exceptoin 클래스들 ex) Java에서 IOException
Kotlin은 체크 예외가 언체크 예외를 구별하지 않는다.
아래와 같이 annotation을 이용해서 명시할 수 있다.
import java.io.IOException
@Throws(IOException::class)
fun mightThrowException() {
// Code that might throw an IOException
}
자바에서는 아래와 같이 명시한다.
import java.io.IOException;
public class Example {
public void mightThrowException() throws IOException {
// Code that might throw an IOException
}
}
fun readNumber(reader: BufferedReader): Int? {
try {
val line = reader.readLine()
return Integer.parseInt(line)
} catch (e: NumberFormatException) {
return null
} finally {
reader.close()
}
}
try 또한 식이기 때문에, try의 값을 변수에 대입할 수 있다.
if와 달리 try의 본문을 반드시 중괄호 { }로 둘러싸야 한다.