ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 7강. 코틀린에서 예외를 다루는 방법
    BackEnd/Kotlin 2024. 2. 7. 22:00
    반응형
    1. try catch finally 구문
    2. Checked Exception과 Unchecked Exception
    3. 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())
        }
      }

     

    감사합니다.

    반응형

    댓글

Designed by Tistory.