1. try catch finally
//java
try {
return Integer.parseInt(str);
} catch (NumberFormatException e) {
throw new IllegalArgumentException("")
}
//kotlin
try {
return str.toInt()
} catch (e: NumberFormatException) {
throw IllegalArgumentException("")
}
- Java와 Kotlin에서 기본적으로 사용하는 구문은 같음
- 차이점
- Kotlin에서 try-catch가 Expression
- new를 사용하지 않고 throw
2. Checked Exception과 Unchecked Exception
//java
public void readFile() throws IOException {
File currentFile = new File(".");
File file = new File(currentFile.getAbsolutePath());
BufferedReader reader = new BufferedReader(new FileReader(file));
System.out.println(reader.readline());
reader.close();
}
//kotlin
fun readFile() {
val currentFile = File(".")
val file = File(currentFile.getAbsolutePath())
val reader = new BufferedReader(FileReader(file))
println(reader.readline())
reader.close()
}
- kotlin은 throws구문이 없음
- checked, uncheck exception을 구분하지 않고 모두 uncheckedException임
3. try with resources
//java
public void readFile (String path) throws IOException{
try (BufferedReader reader = new BufferedReader(new FileReader(path)) {
System.out.println(reader.readLine());
}
}
// kotlin
fun readFile(path : String) {
BufferedReader(FileReader(path)).use {reader ->
println(reader.readLine())
}
}
- kotlin에서는 try - with - resources문이 없고 use라는 inline확장 함수를 사용해야 함
- inline함수, 확장 함수는 section4에서다룸.