Kotlin - Exception

2023. 4. 16. 00:55·📘 Backend/Kotlin

💡 코틀린에서 예외를 다루는법

목차

  • Try Catch Finally
  • Checked & Unchecked Exception
  • Try With Resource

💡 Try Catch Finally

Try-Catch-Finally 문법은 자바,코틀린이 둘 다 동일하며, 코틀린에선 Expression이다.

코틀린에서 try-catch는 Expression이기 떄문에 return이나 변수의 값에 바로 할당이 가능하다


주어진 문자열을 정수로 변경하는 예시

// 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 {
    return try {
        str.toInt()
    } catch (e : NumberFormatException) {
        throw IllegalArgumentException("주어진 ${str}는 숫자가 아납니다.")
    }
}

주어진 문자열을 정수로 변경하는 예시, 실패하면 Null 반환

// Java
private Integer parseIntOrThrowV2(String str) {
    try {
        return Integer.parseInt(str);
    } catch (NumberFormatException e) {
        return null;
    }
}
// Kotlin
fun parseIntOrThrowV2(str : String?) : Int? {
    return try {
        return str?.toInt()
    } catch (e : NumberFormatException e) {
        null
    }
}

💡 Checked Exception & unchecked Exception

코틀린에선 Checked와 Unchecked의 구분이 없고 모두 Unchecked Exception으로 간주한다.

그래서 코틀린에선 throws를 볼 일이 없다.


프로젝트 내 파일의 내용을 읽어오는 예시

// Java
public void readFile() throws IOException {
    File currentFile = new File(".");
    File file = new File(currentFile.getAbsolutePath() + "/a.txt");
    BufferedReader br = new BufferedReader(new FileReader(file));
    System.out.println(br.readLine());
    br.close();
}
// Kotlin
class FilePrint {
    fun readFile() {
        val currentFile = File(".")
        val file = File(currentFile.absolutePath + "/a.txt")
        val br = BufferedReader(FileReader(file))
        println(br.readLine())
        br.close()
    }
}

💡 Try With Resource

코틀린은 Try With Resource 구문이 없기 때문에 use라는 inline 확장함수를 통해 구현한다.


프로젝트 내 파일의 내용을 읽어오는 동일한 예시

// Java
// 외부 리소르를 try() 안에 넣고 try()가 종료되면 자동으로 자원 반환이 이루어진다.
public void readFile(String path) throws IOException {
    try (BufferedReader br = new BufferedReader(new FileReader(path))) {
        System.out.println(br.readLine());
    }
}
// Kotlin
fun readFile(path: String) {
    BufferedReader(FileReader(path)).use {
        br -> println(br.readLine())
    }
}
저작자표시 (새창열림)

'📘 Backend > Kotlin' 카테고리의 다른 글

Kotlin - Class  (0) 2023.04.17
Kotlin - Function  (0) 2023.04.17
Kotlin - Operator  (0) 2023.04.06
Kotlin - Condition  (0) 2023.04.06
Kotlin - Loop  (0) 2023.04.06
'📘 Backend/Kotlin' 카테고리의 다른 글
  • Kotlin - Class
  • Kotlin - Function
  • Kotlin - Operator
  • Kotlin - Condition
신건우
신건우
조용한 개발자
  • 신건우
    우주먼지
    신건우
  • 전체
    오늘
    어제
    • 분류 전체보기 (422)
      • 📘 Frontend (71)
        • Markup (1)
        • Style Sheet (2)
        • Dart (8)
        • Javascript (12)
        • TypeScript (1)
        • Vue (36)
        • React (2)
        • Flutter (9)
      • 📘 Backend (143)
        • Java (34)
        • Concurrency (19)
        • Reflection (1)
        • Kotlin (29)
        • Python (1)
        • Spring (42)
        • Spring Cloud (5)
        • Message Broker (5)
        • Streaming (2)
        • 기능 개발 (5)
      • 💻 Server (6)
        • Linux (6)
      • ❌ Error Handling (11)
      • 📦 Database (62)
        • SQL (31)
        • NoSQL (2)
        • JPQL (9)
        • QueryDSL (12)
        • Basic (4)
        • Firebase (4)
      • ⚙️ Ops (57)
        • CS (6)
        • AWS (9)
        • Docker (8)
        • Kubernetes (13)
        • MSA (1)
        • CI & CD (20)
      • 📚 Data Architect (48)
        • Data Structure (10)
        • Algorithm (8)
        • Programmers (17)
        • BaekJoon (5)
        • CodeUp (4)
        • Design Pattern (4)
        • AI (0)
      • ⚒️ Management & Tool (8)
        • Git (7)
        • IntelliJ (1)
      • 📄 Document (10)
        • Project 설계 (6)
        • Server Migration (3)
      • 📄 책읽기 (2)
        • 시작하세요! 도커 & 쿠버네티스 (2)
      • 🎮 Game (4)
        • Stardew Vally (1)
        • Path of Exile (3)
  • 블로그 메뉴

    • 링크

      • Github
    • 공지사항

    • 인기 글

    • 태그

      GStreamer #Pipeline
      Lock #Thread #Concurrency
      React #Markdown
    • 최근 댓글

    • 최근 글

    • hELLO· Designed By정상우.v4.10.0
    신건우
    Kotlin - Exception
    상단으로

    티스토리툴바