- try catch finally
- Checked Exception / Unchecked Exception
- try with resources
예외
try catch finally
우선 자바 코드를 보자.
1
2
3
4
5
6
7
private int parseIntOrThrow(@NotNull String str) {
try {
return Integer.parseInt(str);
} catch (NumberFormatException e) {
throw new IllegalArgumentExcpetion(String.format("주어진 %s는 숫자가 아닙니다.", str));
}
}
코틀린 코드를 보자.
1
2
3
4
5
6
7
fun parseIntOrThrow(str: String): Int {
try {
return str.toInt()
} catch(e: NumberFormatException) {
throw IllegalArgumentExcpetion("주어진 ${str}은 숫자가 아닙니다.)
}
}
- 기본 타입간의 형 변환은 toType()을 사용한다.
- 타입이 뒤에 위치하며, new 키워드를 사용하지 않는다.
- 포맷팅이 간결하다.
이 외에 다른 부분은 자바와 동일한 것을 볼 수 있다.
다른 예시를 보자.
1
2
3
4
5
6
7
private Integer parseIntOrThrow(String str) {
try {
return Integer.paseInt(str);
} catch (NumberFormatExcpetion e) {
return null;
}
}
1
2
3
4
5
6
7
fun parseIntOrThtow(str: String): Int? {
return try {
str.toInt()
} catch (e: NumberFormatException) {
return null
}
}
- Expression이기 때문에 바로 return 가능하다.
이 외에 try - catch -finally 구문도 마찬가지로 문법은 동일하다.
Checked Exception / UnCheckedException
1
2
3
4
5
6
7
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();
}
위와 같은 자바코드를 예시로 들자. check 예외이기 때문에 throw IOException을 반드시 포함해야 한다.
코틀린을 보자.
1
2
3
4
5
6
7
fun readFile() {
val currentFile = File(".");
val file = File(currentFile.absolutePath + "/a.txt")
val reader = BufferedReader(FileReader(file))
println(reader.readLine())
reader.close()
}
- throws를 명시하지 않아도 IDE에서 에러를 잡지 않는다.
- 코틀린에서는 Checked Exception과 Unchecked Exception을 구분하지 않는다.
- 모두 Unchecked Exception이다.
try with resources
자바 코드 예시를 보자.
1
2
3
4
5
public void readFile(String path) throws IOException {
try (BufferedReader reader = new BufferedReader(new FileReader(path))) {
System.out.println(reader.readLine());
}
}
- try의 괄호 내부에 외부 자원을 만들어주고, try가 종료되면 자동으로 외부 자원을 닫아주는 구문이다.
코틀린에서는 어떻게 할까?
1
2
3
4
5
fun readFile(path: String) {
BufferedReader(FileReader(path)).use { reader ->
println(reader.readLine())
}
}
- 코틀린에는 try with resources 구문이 존재하지 않는다.
- 대신 use라는 메서드가 내부적으로 비슷한 방식으로 동작하도록 해준다.
정리
- try catch finally는 문법적으로 동일하다.
- 하지만 Expression이라는 차이가 있다.
- 코틀린의 모든 예외는 Unchecked Exception이다.
- 코틀린에서 try with resources 구문은 없다. 대신 코틀린의 언어적 특성을 활용해 close를 호출해주는 use 메서드를 사용한다.