1. try-catch, finally
예시 1) 자바와 동일한 형태
fun parseIntOrThrow(str:String): Int {
try{
return str.toInt() // 기본타입간 형변환은 toType사용
}
catch(e:NumberFormatExcpetion){
throw IllegalArgumentException("error")
* 타입이 뒤에 위치
* new를 사용하지 않음
* 포맷팅이 간결
}
}
예시 2) try-catch도 expression형태이므로 return형태로 처리 가능
fun parseIntOrThrowV2(str:String) : Int{
return try {
str.toInt()
}
catch(e:NumberFormatException){
null
}
}
2. chekced, unchecked Excpetion
chekced, unchecked Excpetion 개념
1. chekced Exception
* RuntimeExcpetion의 하위 클래스가 아니면서 Excpetion 클래스의 하위 클래스
* 반드시 에러 처리를 해야하는 특징(try-catch, throw..)을 가지고 있음
- FileNotFoundException: 존재하지 않는 파일의 이름을 입력
- ClassNotFoundException: 실수로 클래스의 이름을 잘못 적음
* 예제) private void test() thows FileNotFoundException{...}
2. unchekced Exception
* RuntimeException의 하위 클래스들을 의미
* 예외처리를 강제하지 않으며, 실행 중(Runtime) 중 발생할 수있는 예외를 의미
- ArrayIndexOutOfBoundsException: 배열의 범위를 벗어났을 때 예외
- NullPointerException: null값을 참조했을 때 예외
자바는 메소드에 Throws표시 여부에 따라 checked와 unchecked Exception이 구분되나, 코틀린에선 구분하지 않음
fun readFile(){
val currentFile = File(".")
val file = File(currentFile.absolutePath + "/a.txt")
val reader = BufferedReader(file)
println(reader.readLine())
reader.close()
}
자바에서는 try-catch로 unchekced Exception을 한번 Wrapping해야되는데, 코틀린은 그럴 필요가 없음
3. try with resources
try with resources?
- try안에 사용할 리소스 객체를 선언하여 사용하는 방식을 의미하며, 작업이 완료되면, 알아서 리소스를 메모리에서 해제
try(BufferedReader reader = new BufferedReader(new FileReader(path))){
...
}
코틀린에서는 try with resources제공하지 않고, .use()라는 inline함수를 사용
fun readerFile(path:String){
BufferedReader reader = new BufferedReader(new FileReader(path)).use{
println(reader.readline())
}
}