반응형
예외를 다루는 방법
try catch finally 구문
Java
private int parseIntOrThrow(@NotNull String str) {
try {
return Integer.parseInt(str);
} catch (NumberFormatException e) {
throw new IllegalArgumentException(String.format("주어진 %s는 숫자가 아닙니다.", str));
}
}
Kotlin
fun parseIntOrThrow(str: String): Int {
try {
return str.toInt()
} catch (e: NumberFormatException) {
throw IllegalArgumentException("주어진 ${str}는 숫자가 아닙니다.")
}
}
fun parseIntOrThrowV2(str: String): Int? {
return try {
str.toInt()
} catch (e: NumberFormatException) {
null
}
}
- 자바와 코틀린의
try catch
구문은 문법적으로 동일하다. - 하지만 코틀린에서
try catch
문은if/else
처럼expression
으로 취급되기 때문에 그대로 리턴할 수 있다.
Checked Exception과 Unchecked Exception
Java
public void readFile() throws IOException {
File currentFile = new File(",");
File file = new File(currentFile.getAbsolutePath() + "/a.txt");
BufferedReader reader = new BufferedReader(new FileReader(file));
System.out.println(reader.readLine());
reader.close();
}
Kotlin
fun readFile() {
val currentFile = File(".")
val file = File(currentFile.absolutePath + "/a.txt")
val reader = BufferedReader(FileReader(file))
println(reader.readLine())
reader.close()
}
- 코틀린은 자바와 다르게 모든
Exception
이Unchecked Exception
이다.- 때문에
throws
를 볼 일이 없다.
- 때문에
try with resources
Java
public void readFileV2(String path) throws IOException {
try (BufferedReader reader = new BufferedReader(new FileReader(path))) {
System.out.println(reader.readLine());
}
}
Kotlin
fun readFileV2(path: String) {
BufferedReader(FileReader(path)).use { reader -> {
println(reader.readLine())
}
}
}
- 코틀린에서는
try with resources
구문이 없다. - 대신
use
라는inline
확장 함수를 사용한다.- 코틀린의 언어적 특징을 활용해 close를 호출해준다.
반응형
'Java & Kotlin > Kotlin' 카테고리의 다른 글
[Kotlin] 상속을 다루는 방법 (0) | 2022.07.06 |
---|---|
[Kotlin] 클래스를 다루는 방법 (0) | 2022.07.06 |
[Kotlin] 함수를 다루는 방법 (0) | 2022.07.06 |
[Kotlin] 반복문을 다루는 방법 (0) | 2022.07.06 |
[Kotlin] 조건문을 다루는 방법 (0) | 2022.07.06 |
[Kotlin] 연산자를 다루는 방법 (0) | 2022.07.05 |