Throwing an exception
Kotlin allows you to manually signal that an exception has occurred.
private fun obtainQuest(
// ...
): String? {
if (playerLevel <= 0) {
throw IllegalArgumentException(
"level must be at least 1"
)
}
// ..
}Handling exceptions
Kotlin allows handling exceptions by the usage of try/catch.
try {
// some code
} catch (e: Exception) {
// handler
} finally {
// optional finally block
}
// `try` is an expression
val a: Int? = try {
input.toInt()
} catch (e: NumberFormatException) {
null
}Preconditions
These functions allow us to define preconditions that must be true before executing some code.
// before:
if (playerLevel <= 0) {
throw IllegalArgumentException(
"level must be at least 1"
)
}
// using the `require` precondition function
require(playerLevel > 0) { // condition
"level must be at least 1"
// ^ Throws an `IllegalArgumentException` if the condition is false.
}| Function | Description |
|---|---|
| check | Throws an IllegalStateException if the argument is false. |
| checkNotNull | Throws an IllegalStateException if the argument is null. Otherwise returns the non-null value. |
| require | Throws an IllegalArgumentException if the argument is false |
| requireNotNull | Throws an IllegalArgumentException if the argument is null, Otherwise returns the non-null value. |
| error | Throws an IllegalArgumentException with a provided message if the argument is null. Otherwise returns the non-value. |
| assert | Throws an AssertionError if the argument is false and the
assertion compiler flag is enabled |
💡 Prefer
IllegalArgumentExceptionwhen you are checking input to a function andIllegalStateExceptionfor most other scenarios.
Defining a custom exception
class InvalidPlayerLevelException() :
IllegalArgumentException("Invalid player level")
// throw the custom exception
throw InvalidPlayerLevelException()