Study Record

[Kotlin] Exception Class (예외 처리) 본문

안드로이드/Kotlin

[Kotlin] Exception Class (예외 처리)

초코초코초코 2023. 8. 9. 10:35
728x90

코틀린의 모든 Exception class 는 Thrwoable 클래스를 상속받는다. 모든 Exception(예외)는 메시지, 스택추적, 선택적 원인을 가지고 있다.

 

 

😶 예외 발생시키기

예외를 발생시키는 것은 throw 표현을 사용한다.

throw Exception("Hi There!")

 

 

😶 예외 잡기

예외가 발생하여 프로그램이 종료되는 것을 막으려면 try...catch 표현을 사용한다.

try {
    // some code
} catch (e: Exception) {
    // handler
} finally {
    // optional finally block
}

try 에 예외가 발생할 가능성이 있는 코드를 적는다. try 문을 실행하는 동안 catch 의 Exception 종류에 따라 예외가 발생했을 때 처리할 수 있는 코드를 적는다. 

 

 

😶 return 값을 가지는 try 문

val a: Int? = try { input.toInt() } catch (e: NumberFormatException) { null }

input.toInt() 가 예외없이 실행되면 메서드 리턴값이 a 의 값이 할당된다. NumberFormatException 예외가 발생하면 null 이 a 에게 할당된다.

 

 

😶 Nothing type

val s = person.name ?: throw IllegalArgumentException("Name required")

예외를 발생시키는 것에 Elvis 표현을 사용할 수 있다. 예외를 발생시키는 부분을 함수로 만들어서 대신 사용할 수도 있다. 

val s = person.name ?: fail("Name required")
println(s)

fun fail(message: String): Nothing {
    throw IllegalArgumentException(message)
}

 

 

 

 

Exceptions | Kotlin

 

kotlinlang.org

 

728x90

'안드로이드 > Kotlin' 카테고리의 다른 글

[Kotlin] Extensions 살펴보기  (0) 2023.08.18
[Kotlin] Enum Class  (0) 2023.08.10
[Kotlin] coroutines 살펴보기  (0) 2023.08.08
[Kotlin] property  (0) 2023.07.21
[Kotlin] object  (0) 2023.07.20