티스토리 뷰

이번 포스팅에서는 코틀린에서 예외를 처리하는 방법에 대해서 알아보자!
1. try catch finally 구문
2. Checked Exception과 Unchecked Exception
3. try with resources 구문
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}는 숫자가 아닙니다.")
}
}

코틀린에서 기본 타입간의 형변환은 toType()
을 사용한다.
또한, 자바에서는 new new IllegalArgumentException
이라 했지만, 코틀린에서는 new
를 사용하지 않는 것을 확인할 수 있다.
Checked Exception과 Unchecked Exception
프로젝트 내 파일의 내용물을 읽어오는 예제
Java
public void readFile() throws IOException {
File currentFile = new File(".");
File file = new File(currentFile.getAbsolutePath() + "/test.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 + "/test.txt")
val reader = BufferedReader(FileReader(file))
println(reader.readLine())
reader.close()
}
코틀린에서는 Checked Exception
과 Unchecked Exception
을 구분하지 않는다.
모두 Unchecked Exception
이기 때문에, 자바에서처럼 throws
를 사용하지 않는다.
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())
}
}

코틀린에서는 자바와 다르게 try with resources
가 없다. 대신 use
라는 inline 확장함수를 사용한다. use
에 대한 자세한 내용은 추후 포스팅할 예정이다.
정리
- 자바와 코틀린 모두
try catch finaly
구문은 문법적으로 완전히 동일하다. - Kotlin에서는
try catch
가expression
이다. - Kotlin에서는 모든 예외가
Unchecked Exception
이다. - Kotlin에서는
try with resources
구문이 없다. 대신, 코틀린의 언어적 특징을 활용해close
를 호출해준다.
'Kotlin' 카테고리의 다른 글
[Kotlin] 클래스 (0) | 2022.06.17 |
---|---|
[Kotlin] object 키워드 (0) | 2022.06.14 |
[Kotlin] 접근 제한자(Visibility Modifier) (0) | 2022.06.07 |
[Kotlin] 반복문 (0) | 2022.06.01 |
[Kotlin] null을 대하는 자세 (0) | 2022.05.28 |
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- 파이썬
- 인프런
- webflux
- kotlin
- 그리디
- 데이터베이스
- spring boot
- 릿코드
- Real MySQL
- 스프링 부트
- 정렬
- 문자열
- 코테
- 자료구조
- 노마드코더
- 스프링
- 리팩토링
- Spring
- 백준
- leetcode
- 구현
- 김영한
- 알고리즘
- Algorithm
- 북클럽
- 노마드
- mysql 8.0
- 코틀린
- MySQL
- 스프링부트
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 |
글 보관함