Exceptions
Kotlin
@kotlin
| Developed by JetBrains
What? Why?
An exception signals that something went exceptionally wrong.
Why use exceptions:
Do NOT use exceptions for:
How?
fun main() {
throw Exception("Hello, world!")
}
Or even better:
fun main() {
val nullableString: String? = null
println("Hello, NPE! ${nullableString!!}")
}
Exception in thread "main" java.lang.NullPointerException
Example
Message: An exception�Cause: java.lang.RuntimeException: A cause�Exception: java.lang.Exception: An exception�Finally always executes�java.lang.Exception: An exception� at MainKt.main(Main.kt:3)� at MainKt.main(Main.kt)�Caused by: java.lang.RuntimeException: A cause� ... 2 more
fun main() {
try {
throw Exception("An exception", RuntimeException("A cause"))
} catch (e: Exception) {
println("Message: ${e.message}")
println("Cause: ${e.cause}")
println("Exception: $e") // toString() is called "under the hood"
e.printStackTrace()
} finally {
println("Finally always executes")
}
}
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 (name.isEmpty() || surname.isEmpty()) {
throw IllegalArgumentException("For blank names/surnames use -")
}
}
}
Dealing with exceptions
You might:
try {
val (n, s, a) = readLine()!!.split('/')
val person = Person(n, s, a.toInt())
addToDataBase(person)
} catch (e: IllegalStateException) {
println("You've entered a negative age! Why?")
} catch (e: IllegalArgumentException) {
println(e.message)
} catch (e: NullPointerException) {
println("NPE ;^)")
} catch (e: Exception) {
println("Something else went wrong")
throw Exception("Failed to add to the database", e)
} finally {
println("See you in the next episodes!")
}
And a lot in java.util
Kotlin sugar
try is an expression:
val a: Int? = try { input.toInt() } 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