Vai al contenuto principale
ProdottiStrumenti desktopTASTECADVisualizzazione disegniTASTEFILESGestione fileTASTEFTPTrasferimento fileTASTESSHSpazio di lavoro remotoTASTEZIPCompressione ed estrazioneTASTEWINMGestione fileStrumenti per sviluppatoriTASTECODEAmbiente di sviluppo integrato per RustTASTESTUDIOAmbiente integrato di sviluppo e testTASTEETLIntegrazione dati (ETL)ServerTASTEREMOTEServer di desktop remotoTASTEGEOServer geospazialeTASTEMAILSpazio di lavoro emailInvestimentiTASTESTOCKApp desktop di trading automatico azionarioIniziaDownloadDocumentazioneAcquistaTutti i prodotti
Marketplace
Notizie
TecnologiaNotizieNotizie di sviluppo di oggiDocumentazioneLinguaggi di programmazioneRustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDartFramework frontend webNext.jsReactVue.js · NuxtSvelteKitAngularFramework serverSpring BootDjangoFastAPIASP.NET CoreNestJS · ExpressFramework per app e desktopTauriFlutterReact NativeElectronAlgoritmiBasi degli algoritmiAlgoritmi fondamentaliAlgoritmi avanzatiAlgoritmi pratici
CommunityProgettiLog di sviluppoPromptProblemi degli strumenti di IAVetrinaGuida alla community
CollaboraTrasferimento tecnicoRealizzazione del sito webRealizzazione di app desktopPipeline di rilascio e pagamentoPartner commercialeContatti
ServiziDesktop remotoPacchetti di installazione su misura
TASTEDEV
Prodotti

Strumenti desktop

TASTECADApri con leggerezza anche i disegni più complessiTASTEFILESSolo i file che servono, alla massima velocitàTASTEFTPLa via più ordinata per i tuoi fileTASTESSHUn legame più solido tra te e i tuoi serverTASTEZIPComprimi più veloce, estrai più sicuroTASTEWINMUn file manager a due pannelli pensato per la tastiera

Strumenti per sviluppatori

TASTECODEModifica, compila, esegui il debug e testa app Rust in un'unica finestraTASTESTUDIODalla modifica ai test remoti e alle correzioni IA approvateTASTEETLSposta i dati guardando i valori

Server

TASTEREMOTEUn desktop remoto che gira sul tuo serverTASTEGEOUn server geospaziale compatibile con GeoServer, ricostruito in RustTASTEMAILRiprendi il controllo della tua posta

Investimenti

TASTESTOCKTrading automatico azionario secondo le regole che decidi tu: quando e che cosa

Inizia

DownloadUltime versioni di ogni prodottoDocsCome usare ogni prodottoAcquistaAbbonamenti e licenze perpetueTutti i prodottiTutti i prodotti a colpo d’occhio
Tutti i prodotti
MarketplaceNotizie
Tecnologia

Notizie

Notizie di sviluppo di oggiAnnunci ufficiali su linguaggi, framework, GitHub e IADocumentazioneGuide a linguaggi, framework e algoritmi

Linguaggi di programmazione

RustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDart

Framework

Framework frontend webNext.jsReactVue.js · NuxtSvelteKitAngular
Framework serverSpring BootDjangoFastAPIASP.NET CoreNestJS · Express
Framework per app e desktopTauriFlutterReact NativeElectron

Algoritmi

Basi degli algoritmiAnalisi della complessità · Ordinamento · Ricerca · Strutture dati di base · Alberi e heapAlgoritmi fondamentaliVisita dei grafi · Cammini minimi e alberi ricoprenti · Programmazione dinamica · Algoritmi greedy · Divide et impera · BacktrackingAlgoritmi avanzatiAlgoritmi sulle stringhe · Matematica e teoria dei numeri · Manipolazione dei bit · Alberi di segmenti · Union-FindAlgoritmi praticiStrategia per colloqui di programmazione · Cache LRU · Rate limiting · Hashing consistente
Tutta la documentazione di sviluppo
Community
ProgettiScopri sviluppatori e lavoriLog di sviluppoDecisioni e lezioni appresePromptIstruzioni riutilizzabiliProblemi degli strumenti di IAProblemi e alternative di Claude, Codex, GeminiVetrinaRisultati completatiGuida alla communityCome sviluppiamo in modo aperto
Collabora
Trasferimento tecnicoApp native in Rust ed eguiRealizzazione del sito web10 lingue, account, documentazione e downloadRealizzazione di app desktopRust ed egui, senza WebViewPipeline di rilascio e pagamentoFirma, MSI, deb, rpm, AppImage, hashPartner commercialeConsigliaci e ricevi il 30%ContattiSviluppo, partnership e investimenti
Servizi
Desktop remotoRaggiungi il tuo computer dal browserPacchetti di installazione su misuraSolo il necessario, impostazioni precaricate
Acquista
IT
한국어EnglishDeutschEspañolFrançaisItalianoPortuguês (Brasil)日本語简体中文繁體中文
Accedi
Accedi
TASTEDEV

Dai piccoli strumenti a uno sviluppo migliore.

support@tastedev.netSostieni TASTEDEV
ProdottiGamma di prodottiAcquistaDocsDownloadMarketplaceAssistenza
CommunityProgettiLog di sviluppoPromptProblemi degli strumenti di IAVetrina
NormeChi siamoInformativa sulla privacyTermini di servizioCondizioni di abbonamentoRimborsiLinee guida della community
AccountAccediRegistrati
Visitatori
Oggi
Ieri
Visualizzazioni totali
Società
GXSOFT
Rappresentante
CHOI YOUNG GU
Numero di registrazione
853-44-00368
Indirizzo
9F V24, 351 Gyeongin-ro, Michuhol-gu, Incheon, Republic of Korea
Telefono
+82-10-4404-1523
E-mail
whitecalvin@tastedev.net
Responsabile privacy
CHOI YOUNG GU

© 2026 TASTEDEVLe informazioni sui prodotti si basano su fonti di sviluppo verificate.Rilasciato · in miglioramento

Documentazione di Kotlin
Kotlin
Getting StartedSyntax BasicsTypes and DataModules and PackagesErrors and TestingKey Concepts
Discussioni

Guida a Kotlin · 5/6

Errors and Testing

Per ora questo capitolo è disponibile solo in inglese.

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
Domande su questo capitolo?
Capitolo precedenteModules and PackagesCapitolo successivoKey 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 commenti

Commenti principaliPrima i più recenti

Accedi · Accedi per lasciare un commento.