Error Handling in Kotlin
Kotlin has no single best way of handling errors – see what we suggest.
Programming comes with two certainties: errors will happen, and they have to be handled well. Errors are an inherent part of software engineering, caused by unpredictable input, system constraints or simply human mistakes. Yet how we deal with them affects not only the quality and maintainability of our code but also the user experience and the reliability of the system. As a modern, expressive language, Kotlin offers several ways of handling errors, from classic try-catch blocks, through more advanced constructs like Result and sealed classes, which let you build custom error models, all the way to Either, a well-known construct from the functional paradigm. In this post, we examine each method more closely, look at its strengths and weaknesses, and try to suggest which option fits a given situation best.
Who is this blog post for?
It is aimed mostly at people who have already made their first steps in Kotlin and want to learn good practices for writing maintainable, extensible code when it comes to processing errors. That said, the approaches described here may also inspire developers working in other languages to apply similar strategies in their own projects.
Why does error handling matter?
Most people in IT have probably come across Murphy’s law, which says: “If something can go wrong, it will”. And I suspect almost everyone in IT would side with Murphy. The phrase strikes a strong chord with software engineers, living in a world where almost impossible edge cases show up, bulletproof systems tend to fail exactly when we least expect it, and our confidence drops sharply – occasionally fuelling our impostor syndrome.
Any seasoned developer knows that errors aren’t merely possible – they are unavoidable. Rather than ignoring them, what matters is accepting them and preparing for them in advance. We may not foresee every particular failure, but designing systems with resilience in mind helps limit the impact of unexpected problems. Obvious as it may sound, this mindset is fundamental to writing maintainable and robust software.
Exceptions in Kotlin: A Short Introduction
Compared to Java, exception handling in Kotlin is simpler and more flexible. Kotlin, unlike Java, treats every exception as unchecked, so you don’t have to declare them in method signatures. This cuts down on boilerplate and keeps method signatures tidier, but it also puts the burden of handling errors on the developer. Let’s look at a short piece of code that reads configuration data from a file at a given path:
fun readConfigFile(filePath: String): Map<String, String> =
FileReader(filePath).use { reader ->
reader.readLines()
.filter { it.contains("=") }
.associate {
val (key, value) = it.split("=", limit = 2)
key.trim() to value.trim()
}
}
As a user of this method, you can’t tell at first sight whether its implementation safely handles possible exceptions. Indeed, apart from the method name, the required parameters and the return type, the signature tells you very little. If you look at the readConfigFile method more carefully, you’ll spot a potential exception that may be thrown but isn’t explicitly handled. To be precise, the FileReader class constructor may throw a FileNotFoundException. The FileReader constructor’s signature states this explicitly:
public FileReader(String fileName) throws FileNotFoundException
Java forces you either to catch the exception explicitly or to declare it in the method signature with throws FileNotFoundException, so that the caller knows the exception may occur. In Kotlin, however, you don’t have to declare or catch such exceptions explicitly, because all exceptions are unchecked. This makes the method signature simpler, but it also means the method’s users must take care of potential exceptions themselves. Armed with this basic knowledge, let’s look at specific ways of handling errors in Kotlin.
The Many Flavors of Error Handling in Kotlin
Try-Catch: The Traditional Approach
This is the most fundamental way to handle errors in Kotlin – familiar, of course, from Kotlin’s older sibling, Java, as well as from many other programming languages. It is a simple tool that most developers already know, and it serves as the first line of defense when dealing with errors.
How does it work?
The syntax is very simple: there is a try clause, in which the developer places code that may throw an exception. When an exception occurs, control flow jumps to the catch block, where the caught exception is waiting to be dealt with properly. The optional last part of try-catch is the finally block, which runs code whether or not an exception was thrown – it is typically used to make sure all resources have been properly cleaned up. Building on the earlier code snippet, using try-catch would look like this:
try {
val config = readConfigFile(configFilePath)
logger.info("Configuration loaded successfully: $config")
} catch (e: FileNotFoundException) {
// Specific handling of file not found error
logger.error("Configuration file not found at path: $configFilePath", e)
} catch (e: Exception) {
// General handling of other unexpected errors
logger.error("An unexpected error occurred while reading the configuration file", e)
}
This way of handling exceptions is simple and easy to understand, even for Kotlin beginners or people coming from Java. It is a sensible place to start with error management, since it lets you deal precisely with particular exceptions (e.g., FileNotFoundException) as well as more general ones from the exception hierarchy, while offering a fallback for unexpected problems. It does have its limitations, though. readConfigFile doesn’t explicitly declare which exceptions it may throw, so the caller needs implicit knowledge of how it behaves. Judging by the method signature, you might think it always returns a Map<String, String>. In practice, that isn’t guaranteed – exceptions may be thrown while it runs, breaking the flow and making the code less predictable. try-catch is intuitive and good enough for many simple cases, but it offers no explicit error tracking. Developers have to depend on implicit knowledge or external documentation to know which exceptions may be thrown, which in more complex scenarios can result in errors being missed or left unhandled. To make code more predictable and tackle these issues, Kotlin provides the Result class, a modern and concise way of explicitly handling both success and failure. Let’s see how this approach makes error handling simpler.
Result: A Better Way of Dealing with Exceptions
try-catch is the traditional, familiar way to manage errors, but Kotlin offers the Result class as a more modern and idiomatic alternative. With Result, developers can express both success and failure as values, which makes error handling explicit and lessens the need for exceptions in many situations. Result lets you model operations that can fail, giving you a cleaner, more functional way of handling errors. Rather than propagating failure through exceptions, a method can return a Result that states explicitly whether the operation succeeded or not.
How does it work?
The Result class makes error handling simpler by wrapping an operation’s outcome so that success and failure are explicitly told apart. Rather than signalling errors with exceptions, Result lets you represent an operation’s outcome as one of two things:
- Success: the operation finished successfully and delivers the expected output.
- Failure: the operation failed, and the exception is wrapped inside the Result object.
To understand it better, let’s rewrite the readConfigFile function so that it uses the Result class:
fun readConfigFile(filePath: String): Result<Map<String, String>> =
runCatching {
FileReader(filePath).use { reader ->
reader.readLines()
.filter { it.contains("=") }
.associate {
val (key, value) = it.split("=", limit = 2)
key.trim() to value.trim()
}
}
}
As you can see, little has changed apart from the method signature and the use of the runCatching function inside readConfigFile. runCatching accepts a block of code that may throw exceptions. It catches any exception thrown while the block runs and returns it as a Result object. When the operation succeeds, runCatching returns a Result object holding the resulting Map<String, String>. When it fails (e.g. the file doesn’t exist), it returns a Result object wrapping the exception. Thanks to this, the signature of readConfigFile states explicitly that it returns Result<Map<String, String>>, so the caller has to deal with success and failure explicitly. Let’s look at it from the caller’s side:
readConfigFile(configFilePath).fold(
onSuccess = { config ->
logger.info("Configuration loaded successfully: $config")
},
onFailure = { exception ->
// Handle errors based on the type of exception
when (exception) {
is FileNotFoundException ->
// Specific handling for file not found errors
logger.error("Configuration file not found at path: $configFilePath", exception)
else ->
// General handling for all other unexpected exceptions
logger.error("An unexpected error occurred while reading the configuration file", exception)
}
}
)
The most important change comes from the new signature of readConfigFile, which forces the returned Result to be handled. The fold method requires both states to be dealt with, so the programmer can’t overlook either Success or Failure. This not only makes handling success and failure explicit but also makes the API clearer. Because the caller has to process both the success and the failure path, fold reduces the chance of missing edge cases or quietly swallowing exceptions. On top of that, it fits Kotlin’s idiomatic functional programming style, so the code becomes more predictable and easier to maintain. What’s more, Result can cut down on traditional try-catch blocks spread throughout the codebase, resulting in a more concise and declarative style of error handling. This is especially valuable in complex systems where errors have to be propagated consistently.
Lastly, a clear split between success and failure states makes testing and debugging easier, since developers can concentrate on each scenario separately, which results in more robust and reliable software. It is worth noting that the Result class offers many more convenient methods for working with Result objects, for example:
- getOrNull: returns the value when the operation succeeded, or null when it failed.
- getOrElse: returns the value on success, or a supplied default value on failure.
- exceptionOrNull: returns the exception when the operation failed, or null when it succeeded.
- onSuccess / onFailure: lets you run side effects depending on success or failure.
- map / mapCatching: transforms the result’s value while keeping the success or failure state.
- recover / recoverCatching: supplies a fallback value or turns the failure into a success.
These are only some of the handy methods offered by the Result class. For the full picture, see the official Kotlin Result API documentation. Result is lightweight and ideal for simple operations, but it has limits in more complex scenarios. In particular, Result isn’t enough when you need to model domain-specific errors carrying rich data, or when the application has to deal with many subtle error cases. In those situations, we need a more structured and exhaustive approach to keep type safety and maintainability as the application grows. For these needs, Kotlin’s sealed classes or sealed interfaces offer a solid framework for modelling complex, domain-specific scenarios.
Sealed Classes: A Structured Approach
Sealed classes offer a robust way of modelling domain-specific scenarios, with every case handled exhaustively. In Kotlin, a sealed class is a special type of class that limits which subclasses may inherit from it. As a result, all possible cases are known at compile time, which makes the code more predictable and type-safe. In contrast to generic approaches such as Result, sealed classes let you model domain-specific scenarios in a way the Kotlin compiler can enforce, guaranteeing that every possible case is handled. As usual, a simple example makes the concept easier to grasp. Picture a simplified e-commerce order processing domain. Suppose we want a method responsible for processing an order. A domain expert has given us a specification saying that, before an order is acknowledged, processing must include these checks:
- Given their age, the user may order the selected product.
- The product must be in stock.
- The payment process completed successfully.
When all these checks pass, the method can return a success result. With this in mind, we can begin modelling our processOrder method.
Modelling Order Processing With Sealed Classes
To start, we define a sealed class representing the outcome of order processing. It will cover every possible outcome, such as success and the various kinds of errors:
sealed class OrderProcessingResult {
data object Success : OrderProcessingResult()
sealed class Error : OrderProcessingResult() {
data object AgeRestriction : Error()
data object PaymentFailed : Error()
data object OutOfStock : Error()
data class SystemError(val reason: String) : Error()
}
}
Then we write a method that processes the order and returns an OrderProcessingResult. It carries out all the required checks, and the result tells us how the operation ended. Such a method might look like this:
class OrderProcessor(
private val agePolicy: AgePolicy,
private val stockService: StockService,
private val paymentService: PaymentService
) {
fun processOrder(order: Order): OrderProcessingResult {
return Result.runCatching {
when {
!agePolicy.isUserAllowedToOrder(order.productId, order.orderingUser) ->
OrderProcessingResult.Error.AgeRestriction
stockService.isNotAvailableInStock(order.productId) ->
OrderProcessingResult.Error.OutOfStock
paymentService.processPayment(order.orderingUser) is PaymentResult.Failure ->
OrderProcessingResult.Error.PaymentFailed
// potentially more logic
else -> OrderProcessingResult.Success
}
}.getOrElse { exception ->
OrderProcessingResult.Error.SystemError("Unexpected error: ${exception.message}")
}
}
}
With this implementation, whoever calls the method has to handle the result. In practice, Kotlin’s when construct is the best choice, since it takes advantage of the compiler’s exhaustiveness checks. Let’s dive in and see how it looks:
when (val processingOrderResult = orderProcessor.processOrder(order)) {
is OrderProcessingResult.Error.AgeRestriction -> {
logger.error("Order failed: User is not allowed to order the product due to age restrictions.")
// Additional logic for handling age restriction cases can be implemented here
}
is OrderProcessingResult.Error.OutOfStock -> {
logger.error("Order failed: The product is out of stock. Product ID: ${order.productId}.")
// Additional logic for handling out-of-stock cases can be implemented here
}
is OrderProcessingResult.Error.PaymentFailed -> {
logger.error("Order failed: Payment processing failed for User: ${order.orderingUser}.")
// Additional logic for handling payment failure cases can be implemented here
}
is OrderProcessingResult.Error.SystemError -> {
logger.error("Order failed: System error occurred - ${processingOrderResult.reason}")
// Additional logic for system error handling can be implemented here
}
is OrderProcessingResult.Success -> {
logger.info("Order processed successfully! Order ID: ${order.orderId}.")
// Additional logic for successful order processing can be implemented here
}
}
}
To sum up, handling the outcomes of processOrder with a sealed class gives you a type-safe, complete mechanism that guarantees every possible case is dealt with explicitly. Together with the when statement, this makes error handling simple and maintainable. By leaving out an else branch, you let the compiler enforce handling of every possible outcome, so the code stays safe as new cases are added.
This approach emphasizes:
- Readability and clarity: every branch of the when statement matches one specific outcome, so the logic explains itself and is easy to follow.
- Scalability: new result types are easy to add, because the Kotlin compiler requires every defined case to be handled. This lowers the chance of overlooked scenarios and encourages safer code.
- Maintainability: the error-handling logic lives in one closed hierarchy, so particular cases are easier to change, test or extend without touching the rest of the code.
Kotlin’s compiler checks guarantee that every case is handled, which lowers the risk of runtime errors and is in line with Kotlin’s design philosophy. As a result, your code is clear, reliable and ready for future requirements, while keeping solid error-handling strategies.
Modelling Order Processing With Either
Sealed classes offer a robust, intuitive way of dealing with multiple outcomes, but Kotlin developers frequently reach for functional programming constructs such as Either, provided by external libraries like arrow-kt. It is meant for situations where the result naturally falls into two separate types: success and failure. Either comes from functional programming paradigms and lets us express these two states in a concise, type-safe way. That makes it a common pick in Kotlin for error handling and functional composition.
Let’s go back to the processOrder example. This time, Either will model the result of processing an order. Replacing the custom sealed class hierarchy with Either lets us simplify how success and failure are represented, while making use of functional-style operations like map, flatMap and fold. This is what the revised code might look like:
sealed class OrderProcessingError {
data object AgeRestriction : OrderProcessingError()
data object PaymentFailed : OrderProcessingError()
data object OutOfStock : OrderProcessingError()
data class SystemError(val reason: String) : OrderProcessingError()
}
class OrderProcessor(
private val agePolicy: AgePolicy,
private val stockService: StockService,
private val paymentService: PaymentService
) {
fun processOrder(order: Order): Either<OrderProcessingError, Unit> =
Result.runCatching {
when {
!agePolicy.isUserAllowedToOrder(order.productId, order.orderingUser) ->
Either.Left(OrderProcessingError.AgeRestriction)
stockService.isNotAvailableInStock(order.productId) ->
Either.Left(OrderProcessingError.OutOfStock)
paymentService.processPayment(order.orderingUser) is PaymentResult.Failure ->
Either.Left(OrderProcessingError.PaymentFailed)
// potentially more logic
else -> Either.Right(Unit)
}
}.getOrElse { exception ->
Either.Left(OrderProcessingError.SystemError("Unexpected error: ${exception.message}"))
}
}
Switching from sealed classes to Either has changed how success and failure are represented in the processOrder method. The most visible difference is the method’s return type, which now explicitly returns Either. This gives a structured, type-safe way of dealing with both the success and the failure state.
By convention, Left stands for the failure state and Right for the success state. Here, processOrder returns an Either whose Left type is OrderProcessingError. This sealed class contains all the error cases from the earlier OrderProcessingResult.Error hierarchy, so every potential error is handled explicitly. The Right type is Unit, meaning there is no particular result representing a successful operation. Previously, success was expressed as OrderProcessingResult.Success, whereas here Unit makes handling success simpler while keeping the design meaningful and clear.
This design decision, however, reveals a trade-off between simplicity and expressiveness. Using Unit for success avoids needless complexity, but it restricts how much meaningful domain-specific information a successful outcome can carry. For example, if the processOrder method had to return an order tracking ID or a detailed success status, a dedicated type on the Right side would be a better fit.
This compromise shows that such choices depend on the particular requirements of the domain. Where success comes with extra context or data, a descriptive type improves clarity and makes future extension easier. Where success carries no meaningful information, on the other hand, Unit is a concise and practical option.
Now that the code uses Either, let’s see how it can be used from the user’s side:
orderProcessor.processOrder(order).fold(
ifLeft = { orderProcessingError ->
when (orderProcessingError) {
OrderProcessingError.AgeRestriction -> {
logger.error("Order failed: User is not allowed to order the product due to age restrictions.")
// Additional logic for handling age restriction cases can be implemented here
}
OrderProcessingError.OutOfStock -> {
logger.error("Order failed: The product is out of stock. Product ID: ${order.productId}.")
// Additional logic for handling out-of-stock cases can be implemented here
}
OrderProcessingError.PaymentFailed -> {
logger.error("Order failed: Payment processing failed for User: ${order.orderingUser}.")
// Additional logic for handling payment failure cases can be implemented here
}
is OrderProcessingError.SystemError -> {
logger.error("Order failed: System error occurred - ${orderProcessingError.reason}")
// Additional logic for system error handling can be implemented here
}
}
},
ifRight = { logger.info("Order processed successfully! Order ID: ${order.orderId}.") }
)
In the revised implementation based on Either, the processOrder result is handled functionally. Earlier, with sealed classes, the client processed results using Kotlin’s when statement, explicitly covering every possible case. With Either, the fold method offers a different approach in line with functional programming paradigms, letting you handle success and failure concisely in two branches. It is worth pointing out, though, that even though Either gives the code a functional flavor, errors are still represented by a sealed class hierarchy, so error states remain explicitly modelled. Besides fold, Either offers a number of key methods that make processing and composing operations easier:
- map: transforms the Right value and leaves the Left as it is.
- flatMap: chains operations returning another Either, which enables composable workflows.
- mapLeft: transforms the Left value and leaves the Right as it is.
- getOrElse: returns the Right value, or a default value in the case of Left.
- swap: exchanges the Left and Right values.
- catch: catches exceptions and turns them into an Either.
These are some of the key methods showing what the Either class can do. For its complete API, see the official Arrow Either API documentation.
As you can see, the Either class has a rich API supporting functional programming, which makes it a great fit for chaining operations, transforming results and dealing with success and failure declaratively. It suits projects that follow a functional approach across the whole codebase particularly well, since using Either only here and there in code that is otherwise imperative can lead to inconsistency. If you want to discover everything it can do, digging into the arrow-kt library and functional programming can unlock even more ways of writing clean, expressive Kotlin code.
Summary: Picking The Right Error Handling Approach
When choosing how to handle errors in Kotlin, it matters to select an approach that matches the complexity of your domain, your team’s preferences and your project’s style. Below is a short comparison to help you decide:
| Approach | Use case | Advantages | Disadvantages |
| try-catch | Basic error handling | Easy to grasp, native to Kotlin | No explicit error tracking, not type-safe |
| Result | Simple success/failure handling | Built in, lightweight | Not very flexible |
| sealed class / interface | Modelling complex domain-specific errors | Type-safe, exhaustive | Needs more setup |
| Either | Composition in a functional style | Powerful, flexible, composable | Demands consistent use of the functional paradigm, steeper learning curve |
When To Pick Each Approach
- Use try-catch: for fast, simple error handling that needs as little code as possible. Works best for scripts or small tasks.
- Use Result: for simple success/failure operations that don’t call for complex error modelling. A great fit for native Kotlin projects.
- Use sealed classes: for applications with rich domain models, where different error states hold meaningful data and exhaustive handling is essential.
- Use Either: when you follow a functional programming paradigm or work with workflows that involve complex transformations or chained operations.
Final Thoughts
Handling errors is crucial for building robust applications, and in Kotlin there is no universal solution. Which approach is best depends on how complex your domain is, what your team prefers and what your project needs. In simpler scenarios, begin with try-catch or Result. Sealed classes bring clarity and type safety to more complex domains, whereas Either and other functional constructs suit teams that embrace a functional programming paradigm. As a first step, analyze your domain, agree with your team on one consistent approach, and put readability first. Start with the simpler tools and move on to advanced libraries such as arrow-kt as your needs grow. Striking a balance between simplicity, expressiveness and maintainability keeps your project clear and robust.