Kotlin
Exceptions
@kotlin | Developed by JetBrains
What? Why?
An exception signals that something went exceptionally wrong.
● Development mistakes
● Errors produced by external (to the program) resources
● System errors
Why use exceptions:
● To separate error-handling code from regular code
● To propagate errors up the call stack – maybe someone knows how to deal with the error
● To group and differentiate error types
Do NOT use exceptions for:
● Control flow
● Manageable errors
How?
fun main() {
throw Exception("Hello, world!")
}
Or even better:
fun main() {
val nullableString: String? = null
println("Hello, NPE! ${nullableString!!}")
}
Exception in thread "main" [Link]
Example
fun main() {
try {
throw Exception("An exception", RuntimeException("A cause"))
} catch (e: Exception) {
println("Message: ${[Link]}")
println("Cause: ${[Link]}")
println("Exception: $e") // toString() is called "under the hood"
[Link]()
} finally { Message: An exception
Cause: [Link]: A cause
println("Finally always executes")
Exception: [Link]: An exception
} Finally always executes
[Link]: An exception
} at
[Link]([Link])
at [Link]([Link])
Caused by: [Link]: A cause
... 2 more
Another meaningful example
data class Person(val name: String, val surname: String, val age: Int) {
init {
if (age < 0) {
throw IllegalStateException("Age cannot be negative")
}
if ([Link]() || [Link]()) {
throw IllegalArgumentException("For blank names/surnames use -")
}
}
}
Dealing with exceptions
try {
val (n, s, a) = readLine()!!.split('/')
val person = Person(n, s, [Link]())
addToDataBase(person)
} catch (e: IllegalStateException) {
println("You've entered a negative age! Why?")
} catch (e: IllegalArgumentException) {
You might:
println([Link])
● Handle the error properly and
} catch (e: NullPointerException) {
println("NPE ;^)") continue execution
} catch (e: Exception) {
println("Something else went wrong") ● Handle something on your side
throw Exception("Failed to add to the database", e)
and re-throw the exception
} finally {
println("See you in the next episodes!")
}
👀
And a lot in [Link]
Kotlin sugar
try is an expression:
val a: Int? = try { [Link]() } catch (e: NumberFormatException) { null }
More sugar:
require(count >= 0) { "Count must be non-negative, was $count" }
// IllegalArgumentException
error("Error message")
// IllegalStateException
Thanks!
@kotlin | Developed by JetBrains