Algus

exceptions

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.
}
FunctionDescription
checkThrows an IllegalStateException if the argument is false.
checkNotNullThrows an IllegalStateException if the argument is null. Otherwise returns the non-null value.
requireThrows an IllegalArgumentException if the argument is false
requireNotNullThrows an IllegalArgumentException if the argument is null, Otherwise returns the non-null value.
errorThrows an IllegalArgumentException with a provided message if the argument is null. Otherwise returns the non-value.
assertThrows an AssertionError if the argument is false and the assertion compiler flag is enabled

💡 Prefer IllegalArgumentException when you are checking input to a function and IllegalStateException for most other scenarios.

Defining a custom exception

class InvalidPlayerLevelException() :
	IllegalArgumentException("Invalid player level")

// throw the custom exception
throw InvalidPlayerLevelException()