Kotlin : 예외

정종욱·2023년 7월 4일
0

Kotlin

목록 보기
7/16
post-thumbnail

Try catch finally

// java
private int parseIntOrThrow(String str) {
	try {
		return Integer.parseInt(str);
	} catch (NumberFormatException e) {
		throw new IllegalArgumentException();
	}
}
// kotlin
fun parseIntOrThrow(str: String): Int {
	try {
    	return str.toInt()
    } catch (e: NumberFormatException) {
    	throw IllegalArgumentException()
    }
}

문법은 완벽하게 동일하나 코틀린이 조금 더 간결하다.

CheckedException & UncheckedException

// java
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.println(reader.readLine());
    reader.close();
}
// kotlin
fun readFile() {
	val currentFile = File(".")
    val file = File(currentFile.absolutePath() + "/a.txt")
    val reader = BufferedReader(FileReader(file))
    println(reader.readLine())
    reader.close()
}

throws 구문이 없다는 차이가 있다. 코틀린에서는 CheckedExceptionUncheckedException 모두 UncheckedException 으로 보기 때문이다.

try with resources

// java
public void readFile(String path) throws IOException {
	try (BufferedReader reader = new BufferedReader(new FileReader(path))) {
    System.out.println(reader.readLine());
  }
}
// kotlin
fun readFile(path: String) {
	BufferedReader(FileReader(path)).use { reader ->
    println(reader.readLine())
    }
}

try with resource 라는 함수가 아닌 코틀린 특성을 이용하여 만든 use 라는 inline 확장함수가 사용된다.

0개의 댓글

관련 채용 정보