本文へスキップ
製品デスクトップツールTASTECAD図面の確認TASTEFILESファイル管理TASTEFTPファイル転送TASTESSHリモートワークスペースTASTEZIP圧縮と展開TASTEWINMファイル管理開発ツールTASTECODERust 統合開発環境TASTESTUDIO統合開発・テスト環境TASTEETLデータ統合(ETL)サーバーTASTEREMOTEリモートデスクトップサーバーTASTEGEO空間情報サーバーTASTEMAILメールワークスペース投資TASTESTOCK株式自動売買デスクトップアプリはじめるダウンロードドキュメント購入すべての製品
マーケットプレイス
ニュース
技術ニュース今日の開発ニュース開発ドキュメントプログラミング言語RustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDartWebフロントエンド フレームワークNext.jsReactVue.js · NuxtSvelteKitAngularサーバー フレームワークSpring BootDjangoFastAPIASP.NET CoreNestJS · Expressアプリ・デスクトップ フレームワークTauriFlutterReact NativeElectronアルゴリズムアルゴリズムの基礎主要アルゴリズム発展アルゴリズム実務のアルゴリズム
コミュニティプロジェクト開発ログプロンプトAIツールの問題ショーケースコミュニティガイド
協業技術移転ウェブサイト構築デスクトップアプリ構築リリース・決済パイプライン販売パートナーお問い合わせ
サービスリモートデスクトップインストールパッケージのカスタマイズ
TASTEDEV
製品

デスクトップツール

TASTECAD複雑な図面を、軽やかにひらくTASTEFILES必要なファイルだけを、最速でTASTEFTPファイルが行き交う、いちばん端正な道TASTESSHサーバーとあなたを、より確かにつなぐTASTEZIPより速くまとめ、より安全にひらくTASTEWINM2つの画面で整理する、キーボード中心のファイルマネージャー

開発ツール

TASTECODERust アプリの編集・ビルド・デバッグ・テストまでひとつのウィンドウでTASTESTUDIO編集からリモートテスト、承認した AI 修正までTASTEETL値を見ながら、データを運ぶ

サーバー

TASTEREMOTE自社サーバーで運用するリモートデスクトップTASTEGEOGeoServer 互換の空間情報サーバーを Rust で作り直しますTASTEMAILメールの主導権を、もう一度自分の手に

投資

TASTESTOCKいつ・何を。自分で決めたルールどおりに動く株式自動売買

はじめる

ダウンロード全製品の最新版ドキュメント各製品の使い方購入サブスクリプション・永久ライセンスすべての製品全製品を一覧で
すべての製品
マーケットプレイスニュース
技術

ニュース

今日の開発ニュース言語・フレームワーク・GitHub・AI の公式発表開発ドキュメント言語・フレームワーク・アルゴリズムのガイド

プログラミング言語

RustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDart

フレームワーク

Webフロントエンド フレームワークNext.jsReactVue.js · NuxtSvelteKitAngular
サーバー フレームワークSpring BootDjangoFastAPIASP.NET CoreNestJS · Express
アプリ・デスクトップ フレームワークTauriFlutterReact NativeElectron

アルゴリズム

アルゴリズムの基礎計算量解析 · ソート · 探索 · 基本データ構造 · 木構造とヒープ主要アルゴリズムグラフ探索 · 最短経路と最小全域木 · 動的計画法 · 貪欲法 · 分割統治法 · バックトラッキング発展アルゴリズム文字列アルゴリズム · 数学と整数論 · ビット演算 · セグメント木 · Union-Find実務のアルゴリズムコーディング面接対策 · LRUキャッシュ · レート制限 · コンシステントハッシュ法
開発ドキュメントをすべて見る
コミュニティ
プロジェクトビルダーと作品を探す開発ログ決定と試行錯誤プロンプト再利用できる指示AIツールの問題Claude・Codex・Gemini の問題と回避策ショーケース完成した成果コミュニティガイドオープンにつくる方法
協業
技術移転Rust・egui でネイティブアプリを作るウェブサイト構築10言語、アカウント、ドキュメントとダウンロードデスクトップアプリ構築Rust・egui、WebView なしリリース・決済パイプライン署名・MSI・deb・rpm・AppImage・ハッシュ販売パートナー紹介して決済額の30%お問い合わせ構築・提携・投資のご相談
サービス
リモートデスクトップブラウザから自分のパソコンへインストールパッケージのカスタマイズ必要な機能だけ、設定は事前に
購入
JA
한국어EnglishDeutschEspañolFrançaisItalianoPortuguês (Brasil)日本語简体中文繁體中文
ログイン
ログイン
TASTEDEV

小さなツールから、より良い開発へ。

support@tastedev.netTASTEDEVを支援
製品製品ラインナップ購入ドキュメントダウンロードマーケットプレイスサポート
コミュニティプロジェクト開発ログプロンプトAIツールの問題ショーケース
ポリシー会社概要プライバシーポリシー利用規約サブスクリプション規約返金ポリシーコミュニティガイドライン
アカウントログイン新規登録
訪問者
今日
昨日
累計閲覧
商号
GXSOFT
代表者
CHOI YOUNG GU
事業者登録番号
853-44-00368
所在地
9F V24, 351 Gyeongin-ro, Michuhol-gu, Incheon, Republic of Korea
電話
+82-10-4404-1523
メール
whitecalvin@tastedev.net
個人情報保護責任者
CHOI YOUNG GU

© 2026 TASTEDEV製品情報は検証済みの開発ソースに基づいています。リリース・改善中

Kotlin ドキュメント
Kotlin
Getting StartedSyntax BasicsTypes and DataModules and PackagesErrors and TestingKey Concepts
ディスカッション

Kotlin ガイド · 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
この章について質問がありますか?
前の章Modules and Packages次の章Key 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件

人気のコメント順新しい順

ログイン · ログインするとコメントできます。