Skip to main content
ProductsDesktop toolsTASTECADDrawing reviewTASTEFILESFile managementTASTEFTPFile transferTASTESSHRemote workspaceTASTEZIPCompression and extractionTASTEWINMFile managementDeveloper toolsTASTECODERust integrated development environmentTASTESTUDIOIntegrated development and test environmentTASTEETLData integration (ETL)ServersTASTEREMOTERemote desktop serverTASTEGEOGeospatial serverTASTEMAILMail workspaceInvestingTASTESTOCKStock auto-trading desktop appGet startedDownloadsDocumentationBuyAll products
Marketplace
News
TechNewsToday's dev newsDeveloper docsProgramming languagesRustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDartWeb front-end frameworksNext.jsReactVue.js · NuxtSvelteKitAngularServer frameworksSpring BootDjangoFastAPIASP.NET CoreNestJS · ExpressApp & desktop frameworksTauriFlutterReact NativeElectronAlgorithmsAlgorithm basicsCore algorithmsAdvanced algorithmsPractical algorithms
CommunityProjectsDevelopment logsPromptsAI tool issuesShowcaseCommunity guide
Work with usTech transferWebsite buildDesktop app buildRelease and payment pipelineSales partnerContact
ServicesRemote desktopCustom installer packages
TASTEDEV
Products

Desktop tools

TASTECADComplex drawings, opened with easeTASTEFILESJust the files you need, as fast as possibleTASTEFTPThe tidiest path for your filesTASTESSHA stronger link between you and your serversTASTEZIPPack faster, unpack saferTASTEWINMA keyboard-first file manager with two panes

Developer tools

TASTECODEEdit, build, debug and test Rust apps in one windowTASTESTUDIOFrom editing to remote tests and approved AI fixesTASTEETLMove data while you watch the values

Servers

TASTEREMOTEA remote desktop you run on your own serverTASTEGEORebuilding a GeoServer-compatible geospatial server in RustTASTEMAILTake back control of your email

Investing

TASTESTOCKStock auto-trading that follows the rules you set: when, and what

Get started

DownloadsLatest builds of every productDocsHow to use each productBuySubscriptions and perpetual licencesAll productsEvery product at a glance
All products
MarketplaceNews
Tech

News

Today's dev newsOfficial announcements on languages, frameworks, GitHub and AIDeveloper docsGuides to languages, frameworks and algorithms

Programming languages

RustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDart

Frameworks

Web front-end frameworksNext.jsReactVue.js · NuxtSvelteKitAngular
Server frameworksSpring BootDjangoFastAPIASP.NET CoreNestJS · Express
App & desktop frameworksTauriFlutterReact NativeElectron

Algorithms

Algorithm basicsComplexity analysis · Sorting · Searching · Basic data structures · Trees and heapsCore algorithmsGraph traversal · Shortest paths & minimum spanning trees · Dynamic programming · Greedy algorithms · Divide and conquer · BacktrackingAdvanced algorithmsString algorithms · Math and number theory · Bit manipulation · Segment trees · Union-findPractical algorithmsCoding interview strategy · LRU cache · Rate limiting · Consistent hashing
All development docs
Community
ProjectsDiscover builders and their workDevelopment logsDecisions and lessons learnedPromptsReusable instructionsAI tool issuesProblems and workarounds for Claude, Codex, GeminiShowcaseFinished resultsCommunity guideHow we build in the open
Work with us
Tech transferNative apps in Rust and eguiWebsite build10 languages, accounts, docs and downloadsDesktop app buildRust and egui, no WebViewRelease and payment pipelineSigning, MSI, deb, rpm, AppImage, hashesSales partnerRecommend us and earn 30%ContactBuilds, partnerships and investment
Services
Remote desktopReach your computer from a browserCustom installer packagesOnly the features you need, settings preloaded
Buy
EN
한국어EnglishDeutschEspañolFrançaisItalianoPortuguês (Brasil)日本語简体中文繁體中文
Log in
Log in
TASTEDEV

From small tools to better development.

support@tastedev.netSupport TASTEDEV
ProductsProduct lineupBuyDocsDownloadsMarketplaceSupport
CommunityProjectsDevelopment logsPromptsAI tool issuesShowcase
PoliciesAbout usPrivacy policyTerms of serviceSubscription termsRefund policyCommunity guidelines
AccountLog inSign up
Visitors
Today
Yesterday
Total views
Company
GXSOFT
Representative
CHOI YOUNG GU
Business registration number
853-44-00368
Address
9F V24, 351 Gyeongin-ro, Michuhol-gu, Incheon, Republic of Korea
Phone
+82-10-4404-1523
Email
whitecalvin@tastedev.net
Privacy officer
CHOI YOUNG GU

© 2026 TASTEDEVProduct information is based on verified development sources.Released · improving

Kotlin docs
Kotlin
Getting StartedSyntax BasicsTypes and DataModules and PackagesErrors and TestingKey Concepts
Discussions

Kotlin guide · 5/6

Errors and Testing

This chapter looks at exceptions in Kotlin, at modeling failure as a value with Result, at the precondition helpers require and check, and at writing tests with kotlin.test.

Exceptions, minus the checked ones

throw, try, catch and finally work much as in Java. The big difference is that Kotlin has no checked exceptions: functions never declare what they throw, and callers are never forced to catch anything.

class InsufficientFundsException(val shortage: Long) :
    Exception("Short by $shortage")

fun withdraw(balance: Long, amount: Long): Long {
    if (amount > balance) throw InsufficientFundsException(amount - balance)
    return balance - amount
}

fun main() {
    try {
        withdraw(1_000, 5_000)
    } catch (e: InsufficientFundsException) {
        println(e.message)     // Short by 4000
    } finally {
        println("Transaction closed")
    }
}

If Java callers need to catch a checked exception from your Kotlin function, annotate it with @Throws(IOException::class) so the Java compiler knows about it.

try is an expression

Like if and when, try yields a value: the last expression of the try block or of the matching catch. throw is an expression too, of type Nothing, so it fits anywhere an expression is expected.

fun parsePort(text: String): Int {
    val port = try {
        text.toInt()
    } catch (e: NumberFormatException) {
        8080                     // fall back to the default port
    }
    return port
}

fun fail(message: String): Nothing = throw IllegalStateException(message)

fun main() {
    println(parsePort("9000"))   // 9000
    println(parsePort("abc"))    // 8080
}

A function returning Nothing never completes normally, and the compiler uses that fact to treat code after the call as unreachable.

require, check and error

The standard library ships small helpers for preconditions. They throw the appropriate exception when a condition is false and state your intent more clearly than a hand-written if plus throw.

FunctionThrowsUse it for
require(condition)IllegalArgumentExceptioninvalid arguments
check(condition)IllegalStateExceptioninvalid object state
requireNotNull(value)IllegalArgumentExceptionarguments that must not be null
error(message)IllegalStateExceptioncode that should be unreachable
class Account(initial: Long) {
    var balance = initial
        private set
    private var closed = false

    init {
        require(initial >= 0) { "Initial balance must not be negative: $initial" }
    }

    fun deposit(amount: Long) {
        require(amount > 0) { "Deposit must be positive" }
        check(!closed) { "Account is closed" }
        balance += amount
    }

    fun close() {
        if (closed) error("Account already closed")
        closed = true
    }
}

Messages are passed as lambdas, so the string is only built when the check fails. private set makes the property readable everywhere but writable only inside the class.

runCatching and Result

When failure is common and expected, you can treat it as data instead of throwing. runCatching runs a block and wraps either its value or the caught exception in a Result<T>.

import java.io.File

fun main() {
    val result: Result<String> = runCatching { File("app.conf").readText() }

    result
        .onSuccess { println("Read ${it.length} characters") }
        .onFailure { println("Could not read: ${it.message}") }

    val text = result.getOrElse { "default config" }
    val lineCount = result.map { it.lines().size }.getOrDefault(0)
    println("$text / $lineCount")
}

Result also offers isSuccess, getOrNull, exceptionOrNull and fold. One caveat: runCatching catches every Throwable, so inside coroutines take care not to swallow CancellationException, which is how cancellation is signaled.

Testing with kotlin.test

kotlin.test is a test library with the same API on every platform; on the JVM it runs on top of JUnit. The Gradle setup is short:

// build.gradle.kts
dependencies {
    testImplementation(kotlin("test"))
}

tasks.test {
    useJUnitPlatform()
}

With useJUnitPlatform(), the Kotlin Gradle plugin picks the JUnit 5 flavor of kotlin-test for you. Tests go under src/test/kotlin.

// src/test/kotlin/AccountTest.kt
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith

class AccountTest {
    @Test
    fun `deposit increases the balance`() {
        val account = Account(1_000)
        account.deposit(500)
        assertEquals(1_500L, account.balance)
    }

    @Test
    fun `non-positive deposits are rejected`() {
        val account = Account(0)
        val e = assertFailsWith<IllegalArgumentException> {
            account.deposit(-1)
        }
        assertEquals("Deposit must be positive", e.message)
    }
}

Backtick-quoted function names can be full sentences, which makes test reports easy to read. Run everything with ./gradlew test. Popular additions include Kotest for richer assertions and test styles, MockK for mocking, and runTest from kotlinx-coroutines-test for coroutine code.

Summary

  • Kotlin has no checked exceptions: no throws clauses and no forced catch blocks.
  • try and throw are expressions, so their results can be assigned or used after the Elvis operator.
  • Use require for arguments, check for state, and error for unreachable code.
  • runCatching wraps outcomes in Result; avoid swallowing cancellation inside coroutines.
  • Write tests with @Test, assertEquals and assertFailsWith from kotlin.test, and run them with ./gradlew test.
Questions about this chapter?
Previous chapterModules and PackagesNext chapterKey Concepts

0 comments

Top commentsNewest first

Sign in · Sign in to leave a comment.