포스트

Kotlin의 예외 다루기


try catch finally 구문


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


Java

1
2
3
4
5
6
7
private int parsIntOrThrow(@NotNull String str) {
    try{
        return Integer.parseInt(str);
    }catch(NumberFormatException e) {
       throw new IllegalArgumentException(String.format("주어진 %s는 숫자가 아닙니다", str)); 
    }
  }


Kotlin 으로 변경

1
2
3
4
5
6
7
fun parseIntOrThrow(str: String): Int {
    try{
        return str.toInt()
    }catch (e: NumberFormatException){
        throw IllegalArgumentException("주어진 ${str}는 숫자가 아닙니다")
    }
}
  1. 형변환 toType()사용
  2. 타입은 뒤에 위치하도록 하고, new사용 안함
  3. try-catch의 문법은 동일


주어진 문자열을 정수로 변경하는 예제 (실패 시, null 반환)


Java

1
2
3
4
5
6
7
private int parsIntOrThrow(@NotNull String str) {
    try{
        return Integer.parseInt(str);
    }catch(NumberFormatException e) {
       return null;
    }
  }


Kotlin 으로 변경

1
2
3
4
5
6
7
fun parseIntOrThrowV2(str: String): Int? {
    return try{
        str.toInt()
    }catch (e: NumberFormatException){
        null
    }
}
  • try-catch또한 expression으므로 try-catch문 자체를 return할 수 있다.




Checked Exception / Unchecked Exception


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


Java

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.printIn(reader.readLine());
    reader.close();
  }


Kotlin 으로 변경

1
2
3
4
5
6
7
8
fun readFile(){
    val currentFile = File(".")
    // absolutePath -> 절대 경로
    val file = File(currentFile.absolutePath + "/a.txt")
    val reader = BufferedReader(FileReader(file))
    println(reader.readLine())
    reader.close()
}
  1. throws구문이 없음
    • Kotlin은 Checked Exception / Unchecked Exception의 구분이 없다!!
    • 모두 Unchecked Exception으로 간주




try with resources


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


Java

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());
    }
  }

직접 경로를 받아 경로를 통해서 FileReader가 최종 내용물을 읽어 온다.


Kotlin 으로 변경

1
2
3
4
fun readFileV2(path: String){
  BufferedReader(FileReader(path)).use { reader ->
    println(reader.readLine())
  }

Kotlin에서는 try with resources가 사라지고 use (inline 확장함수)를 사용

이 기사는 저작권자의 CC BY 4.0 라이센스를 따릅니다.