본문 바로가기

공부방/Kotlin

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

try - catch


try-catch 문법은 자바와 코틀린 모두 동일합니다.

다만 코틀린에서는 try-catch 문법을 Expression으로 취급한다는 것에 약간의 차이가 있습니다.

 

[Java]

 

 

[Kotlin]

 

 

Checked Exception, Unchecked Exception


코틀린에서는 checked exception이 존재하지 않습니다.

코드를 통해 확인해 보도록 하겠습니다.

 

[Java]

여기 파일을 읽어내는 코드가 있습니다.

자바에서는 IOException 예외처리를 진행해야 코드를 실행할 수 있습니다.

코틀린에서는 어떨까요?

 

 

public class Lec07Main {

  public static void main(String[] args) throws IOException {
	  File currentFile = new File(".");
	  File file = new File(currentFile.getAbsoluteFile() + "/a.txt");
	  BufferedReader reader = new BufferedReader(new FileReader(file));
	  System.out.println(reader.readLine());
	  reader.close();
  }
}

 

[Kotlin]

위에서 말한 것과 동일하게 자바에는 Checked Exception이 존재하지 않습니다.

그렇기 때문에 IOException을 throw 하지 않아도 문제가 발생하지 않습니다.

 

fun main() {
	// kotlin은 모두 unchecked exception으로 간주한다.
	// IOException이 나옴에도 불구하고 예외처리를 해주지 않아도 된다.
	val currentFile = File(".")
	val file = File("${currentFile.absolutePath}/a.txt")
	val reader = BufferedReader(FileReader(file))
	println(reader.readLine())
	reader.close()
}

 

 

try-with-resources


자바에서는 try-with-resources라는 문법이 있습니다.

일반적으로 파일을 읽고 쓰고 할 때, resource를 열고 닫는 작업을 간편하게 하기 위해서 사용하는 문법입니다.

kotlin에서는 이러한 문법이 없는데요, try-with-resources를 사용하지 않고 어떻게 대체할 수 있는지 알아보도록 하겠습니다.

 

[Java]

여기 파일의 경로를 인자로 받아서 파일을 읽어내는 코드가 있습니다.

 

public class Lec07Main {
  public void readFile(String path) throws IOException {
	  try (BufferedReader reader = new BufferedReader(new FileReader(path))) {
		  System.out.println(reader.readLine());
	  }
  }
}

 

[Kotlin]

코틀린에서는 try-with-resources 문법이 존재하지 않습니다.

대신 use 라는 inline 확장함수를 사용해서 구현할 수 있습니다.

 

fun fileReader(path: String) {
	BufferedReader(FileReader(path)).use {reader ->
		println(reader.readLine())
	}
}