[기초] 코틀린에서 예외를 다루는 방법

정리

- try catch finally 구문은 문법적으로 완전히 동일하다
→ Kotlin에서는 try catch가 expression이다
- Kotlin에서 모든 예외는 Uncheked Exception이다
- Kotlin에서는 try with resources 구문이 없고, 코틀린의 언어적 특징을 활용해 close를 호출해준다

 

try catch finally 구문

주어진 문자열을 정수로 변경해보자 

fun parseIntOrThrow(str: String): Int {
    try{
    	return str.toInt()
    } catch (e: NumberFormatException) {
    	throw IllegalArgumentException("주어진 ${str}은 숫자가 아닙니다")
    }
}

- 기본 타입간의 형 변환은 toType()을 사용

- exception도 타입이 뒤에 위치하고 new를 사용하지 않고, 포맷팅이 간결하다

 

똑같은 예제에서 null을 반환해보자

fun parseIntOrThrow2(str: String): Int? {
    return try{
    	str.toInt()
    } catch (e: NumberFormatException) {
    	null
    }
}

Kotlin에서는 try catch 구문 역시 expression이다

 

Checked Exception과 Unchecked Exception

프로젝트 내 파일의 내용을 읽어오는 코드를 작성해보자

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

자바에서는 위와 같은 로직이다.

 

코틀린은 아래와 같다.

fun readFile() {
    val currentFile = File(".")
    val file = File(currentFile.absolutePath + "/a.txt")
    val reader = BufferedReader(FileReader(file))
    
    println(reader.readLine())
    reader.close()
}

 

Java에서와는 달리 throws 구문이 없다.

 

Kotlin에서는 Checked Exception과 Unchecked Exception을 구분하지 않고,

모두 Unchecked Exception이다.

 

try with resources

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

Kotlin에서는 try with resources가 사라지고 use 라는 inline 함수를 사용한다