HomeAboutMeBlogGuest
© 2025 Sejin Cha. All rights reserved.
Built with Next.js, deployed on Vercel
📝
남득윤 학습 저장소
/
Kotlin docs
Kotlin docs
/
▶️
Exceptions
▶️

Exceptions

 

Exception classes

코틀린의 모든 예외 클래스는 Throwable 클래스를 상속합니다.
모든 예외는 메시지와 스택 트레이스를 가집니다. cause 는 선택적으로 가집니다.
 
fun main() { for (i in 1..3) { print(i) } throw Exception("Hi There!") }
123Exception in thread "main" java.lang.Exception: Hi There!
 
try...catch 구문으로 예외를 잡을 수 있습니다
try { // some code } catch (e: SomeException) { // handler } finally { // optional finally block }
catch 블락, finally 블락을 생략 할 수 있지만 둘중에 하나는 꼭 있어야 합니다.
 
try 도 표현식입니다. 즉, 리턴 값을 가질 수 있습니다.
val a: Int? = try { input.toInt() } catch (e: NumberFormatException) { null }
try catch 구문의 리턴 값은 블락의 마지막 표현식 값입니다.
finally block 의 내용은 리턴 값에 영향을 주지 않습니다.
 

Checked exceptions

코틀린은 Checked 예외가 없습니다.
 
And here are some additional thoughts on the matter:
  • Java's checked exceptions were a mistake (Rod Waldhoff)
  • The Trouble with Checked Exceptions (Anders Hejlsberg)
 

The Nothing type

throw 도 표현식입니다. 값을 가질 수 있습니다.
예를들어 이렇게 엘비스 연산자 안에서 사용할 수 있습니다.
val s = person.name ?: throw IllegalArgumentException("Name required")
 
Nothing을 값을 리턴하면 안되는 함수에 사용해서 마킹용으로 사용할 수 있습니다.
fun fail(message: String): Nothing { throw IllegalArgumentException(message) }
 
val s = person.name ?: fail("Name required") println(s) // 's' is known to be initialized at this point
 
  • Nothing?
val x = null // 'x' has type `Nothing?` val l = listOf(null) // 'l' has type `List<Nothing?>