-
7강. 코틀린에서 예외를 다루는 방법BackEnd/Kotlin 2024. 2. 7. 22:00반응형
- try catch finally 구문
- Checked Exception과 Unchecked Exception
- try with resources
try catch finally 구문
try catch finally 문법 자체는 Java와 Kotlin 모두 동일합니다. 단, Kotlin의 try catch는 if-else 혹은 if-else if-else 처럼 하나의 Expression 으로 간주됩니다.
다음은 Java로 작성된 예외를 처리하는 예제 코드입니다.
private int parseIntOrThrow(@NotNull String str) { try { return Integer.parseInt(str); } catch (NumberFormatException e) { throw new IllegalArgumentException(String.format("주어진 %s는 숫자가 아닙니다.", str)); } } private Integer parseIntOrThrow2(@NotNull String str) { try { return Integer.parseInt(str); } catch (NumberFormatException e) { return null; } }
Kotlin으로 작성하면 다음과 같습니다.
fun parseIntOrThrow(str: String): Int { try { return str.toInt() } catch (e: java.lang.NumberFormatException) { throw java.lang.IllegalArgumentException("주어진 ${str}는 숫자가 아닙니다.") } } fun parseIntOrThrow2(str: String): Int? { // Expression return try { str.toInt() } catch (e: java.lang.NumberFormatException) { null } }
Checked Exception과 Unchecked Exception
Kotlin에서는 Checked Exception과 Unchecked Exception을 구분하지 않습니다. 모두 Unchecked Exception 입니다.
다음은 프로젝트 내 파일의 내용물을 읽어오는 예제 코드입니다. Java는 Checked Exception에 대한 처리를 하지만, Kotlin은 하지 않습니다.
// Java public static void main(String[] args) throws IOException { readFile(); } public static 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 main() { readFile() } fun readFile() { val currentFile = File(".") val file = File(currentFile.absolutePath + "/a.txt") val reader = BufferedReader(FileReader(file)) println(reader.readLine()) reader.close() }
try with resources
Kotlin에는 try with resources 구문이 없습니다. 대신 use 라는 inline 확장 함수를 사용합니다.
// Java: try with resources (JDK 7) public void readFile(String path) throws IOException { try (BufferedReader reader = new BufferedReader(new FileReader(path))) { System.out.println(reader.readLine()); } } // Kotlin: use fun readFile(path: String) { BufferedReader(FileReader(path)).use { reader -> println(reader.readLine()) } }
감사합니다.
반응형'BackEnd > Kotlin' 카테고리의 다른 글
9강. 코틀린에서 클래스를 다루는 방법 (0) 2024.03.03 8강. 코틀린에서 함수를 다루는 방법 (0) 2024.02.21 6강. 코틀린에서 반복문을 다루는 방법 (0) 2024.02.05 5강. 코틀린에서 조건문을 다루는 방법 (1) 2024.02.04 4강. 코틀린에서 연산자를 다루는 방법 (0) 2024.01.31