Zum Hauptinhalt springen
ProdukteDesktop-WerkzeugeTASTECADZeichnungsprüfungTASTEFILESDateiverwaltungTASTEFTPDateiübertragungTASTESSHRemote-ArbeitsbereichTASTEZIPKomprimieren und EntpackenTASTEWINMDateiverwaltungEntwicklerwerkzeugeTASTECODEIntegrierte Entwicklungsumgebung für RustTASTESTUDIOIntegrierte Entwicklungs- und TestumgebungTASTEETLDatenintegration (ETL)ServerTASTEREMOTERemote-Desktop-ServerTASTEGEOGeodatenserverTASTEMAILE-Mail-ArbeitsbereichInvestierenTASTESTOCKDesktop-App für automatischen AktienhandelErste SchritteDownloadsDokumentationKaufenAlle Produkte
Marktplatz
Neuigkeiten
TechnikNeuigkeitenEntwickler-News von heuteEntwicklerdokuProgrammiersprachenRustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDartWeb-Frontend-FrameworksNext.jsReactVue.js · NuxtSvelteKitAngularServer-FrameworksSpring BootDjangoFastAPIASP.NET CoreNestJS · ExpressApp- & Desktop-FrameworksTauriFlutterReact NativeElectronAlgorithmenAlgorithmus-GrundlagenKernalgorithmenFortgeschrittene AlgorithmenAlgorithmen für die Praxis
CommunityProjekteEntwicklungslogsPromptsProbleme mit KI-ToolsShowcaseCommunity-Leitfaden
ZusammenarbeitWissenstransferWebsite-AufbauDesktop-App-AufbauRelease- und ZahlungspipelineVertriebspartnerKontakt
DiensteRemote-DesktopIndividuelle Installationspakete
TASTEDEV
Produkte

Desktop-Werkzeuge

TASTECADKomplexe Zeichnungen, mühelos geöffnetTASTEFILESNur die Dateien, die zählen – in BestzeitTASTEFTPDer aufgeräumteste Weg für Ihre DateienTASTESSHDie stärkere Verbindung zu Ihren ServernTASTEZIPSchneller packen, sicherer entpackenTASTEWINMEin tastaturorientierter Dateimanager mit zwei Fenstern

Entwicklerwerkzeuge

TASTECODERust-Apps bearbeiten, bauen, debuggen und testen – alles in einem FensterTASTESTUDIOVom Bearbeiten bis zu Remote-Tests und freigegebenen KI-KorrekturenTASTEETLDaten bewegen, die Werte im Blick

Server

TASTEREMOTEEin Remote-Desktop auf Ihrem eigenen ServerTASTEGEOEin GeoServer-kompatibler Geodatenserver, neu aufgebaut in RustTASTEMAILIhre E-Mail wieder in Ihrer Hand

Investieren

TASTESTOCKAutomatischer Aktienhandel nach Ihren Regeln: wann und was

Erste Schritte

DownloadsNeueste Versionen aller ProdukteDokuSo nutzen Sie jedes ProduktKaufenAbos und DauerlizenzenAlle ProdukteAlle Produkte im Überblick
Alle Produkte
MarktplatzNeuigkeiten
Technik

Neuigkeiten

Entwickler-News von heuteOffizielle Meldungen zu Sprachen, Frameworks, GitHub und KIEntwicklerdokuAnleitungen zu Sprachen, Frameworks und Algorithmen

Programmiersprachen

RustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDart

Frameworks

Web-Frontend-FrameworksNext.jsReactVue.js · NuxtSvelteKitAngular
Server-FrameworksSpring BootDjangoFastAPIASP.NET CoreNestJS · Express
App- & Desktop-FrameworksTauriFlutterReact NativeElectron

Algorithmen

Algorithmus-GrundlagenKomplexitätsanalyse · Sortieren · Suchen · Grundlegende Datenstrukturen · Bäume und HeapsKernalgorithmenGraphtraversierung · Kürzeste Wege und minimale Spannbäume · Dynamische Programmierung · Greedy-Algorithmen · Teile und herrsche · BacktrackingFortgeschrittene AlgorithmenZeichenkettenalgorithmen · Mathematik und Zahlentheorie · Bitmanipulation · Segmentbäume · Union-FindAlgorithmen für die PraxisStrategie für Coding-Interviews · LRU-Cache · Rate Limiting · Konsistentes Hashing
Alle Entwicklungsdokumente
Community
ProjekteEntwickler und Projekte entdeckenEntwicklungslogsEntscheidungen und ErkenntnissePromptsWiederverwendbare AnweisungenProbleme mit KI-ToolsProbleme und Workarounds für Claude, Codex, GeminiShowcaseFertige ErgebnisseCommunity-LeitfadenWie wir offen entwickeln
Zusammenarbeit
WissenstransferNative Apps mit Rust und eguiWebsite-Aufbau10 Sprachen, Konten, Dokumentation und DownloadsDesktop-App-AufbauRust und egui, ohne WebViewRelease- und ZahlungspipelineSignatur, MSI, deb, rpm, AppImage, PrüfsummenVertriebspartnerEmpfehlen und 30 % erhaltenKontaktEntwicklung, Partnerschaft, Investition
Dienste
Remote-DesktopIhren Computer im Browser erreichenIndividuelle InstallationspaketeNur nötige Funktionen, Einstellungen vorab
Kaufen
DE
한국어EnglishDeutschEspañolFrançaisItalianoPortuguês (Brasil)日本語简体中文繁體中文
Anmelden
Anmelden
TASTEDEV

Von kleinen Werkzeugen zu besserer Entwicklung.

support@tastedev.netTASTEDEV unterstützen
ProdukteProduktübersichtKaufenDokuDownloadsMarktplatzSupport
CommunityProjekteEntwicklungslogsPromptsProbleme mit KI-ToolsShowcase
RichtlinienÜber unsDatenschutzerklärungNutzungsbedingungenAbo-BedingungenRückerstattungCommunity-Richtlinien
KontoAnmeldenRegistrieren
Besucher
Heute
Gestern
Aufrufe gesamt
Firma
GXSOFT
Vertretungsberechtigt
CHOI YOUNG GU
Handelsregisternummer
853-44-00368
Anschrift
9F V24, 351 Gyeongin-ro, Michuhol-gu, Incheon, Republic of Korea
Telefon
+82-10-4404-1523
E-Mail
whitecalvin@tastedev.net
Datenschutzbeauftragter
CHOI YOUNG GU

© 2026 TASTEDEVProduktinformationen basieren auf verifizierten Entwicklungsquellen.Veröffentlicht · wird verbessert

Kotlin-Dokumentation
Kotlin
Getting StartedSyntax BasicsTypes and DataModules and PackagesErrors and TestingKey Concepts
Diskussionen

Kotlin-Anleitung · 5/6

Errors and Testing

Dieses Kapitel ist vorerst nur auf Englisch verfügbar.

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
Fragen zu diesem Kapitel?
Vorheriges KapitelModules and PackagesNächstes KapitelKey Concepts
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.

0 Kommentare

Top-KommentareNeueste zuerst

Anmelden · Melde dich an, um einen Kommentar zu schreiben.