Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Kotlin Exception Handling

Kotlin Exception Handling

Exceptions are unexpected situations that occur while a program is running. Kotlin uses try-catch to capture them so the program can continue executing after an error.

Compared with Java, Kotlin's biggest difference is that it has no checked exceptions; the compiler no longer forces you to declare, for every method, the exceptions it might throw.

This chapter covers everything from the exception hierarchy to automatic resource closing, including all exception-handling techniques used in everyday development.


Exception hierarchy

Kotlin's exception system is consistent with the JVM; the root type is Throwable, which branches into Error and Exception.

Kotlin exception hierarchy tree: Throwable is split into Exception and Error; Exception has RuntimeException and IOException beneath it, while Error has OutOfMemoryError and StackOverflowError

Type Meaning Typical subclass Should it be caught
Throwable The root type of all throwable objects Exception、Error Generally not caught directly
Error Serious errors at the JVM level that a program usually cannot recover from OutOfMemoryError、StackOverflowError Not recommended to catch
Exception Problems caused by program logic or the runtime environment, which can be recovered from IOException、IllegalArgumentException Should be handled
RuntimeException Exceptions that only surface at runtime; Kotlin has no checked exceptions, and the vast majority of exceptions belong to this branch NullPointerException、IndexOutOfBoundsException Handle as needed

Tip:Do not catch Error along with everything else. Problems like out-of-memory and stack overflow cannot be recovered from even if caught, and catching them only masks the real fault.


try-catch-finally

The try block holds code that may fail, catch blocks match by exception type in order, and the finally block executes whether or not an exception occurs.

catch matching proceeds from top to bottom, so subtypes must be written before supertypes.

Example

fun main

(

)

{

   

// Process three kinds of input in turn and observe which catch branch matches

    val inputs

=

listOf

(

"42"

,

"runoob"

,

null

)

   

for

(

input in inputs

)

{

       

try

{

           

// input is String?, and !! throws NullPointerException when it encounters null

            val value

:

Int

=

input

!!

.

toInt

(

)

            println

(

"$input converted successfully: $value"

)

       

}

catch

(

e

:

NumberFormatException

)

{

           

// Reached here when the string is not a valid number

            println

(

"Number format error: ${e.message}"

)

       

}

catch

(

e

:

NullPointerException

)

{

            println

(

"Encountered a null value"

)

       

}

finally

{

           

// Executes whether the result is success or failure, suitable for cleanup logic

            println

(

"--- Finished one round ---"

)

       

}

   

}

    println

(

"Loop ended, program continues running"

)

}



42 转换成功:42

--- Finished one round ---

数字格式错误:For input string: "runoob"

--- Finished one round ---

遇到 null 值

--- Finished one round ---

循环结束,程序继续运行

If an exception is not matched by any catch branch, it keeps propagating up to the caller, eventually terminating the program and printing a stack trace.


try as an expression

In Kotlin, try is an expression rather than a statement. It can have a return value, which is the result of the last expression in the try or catch block.

This lets logic like "try to convert, and use a default value on failure" be written very compactly.

Example

// The return value of try is used directly as the function's return value

fun parseAge

(

text

:

String

)

:

Int

{

   

return

try

{

        text.

toInt

(

)

         

// The value of the whole try expression on success

   

}

catch

(

e

:

NumberFormatException

)

{

       

1

                   

// The value of the whole try expression on failure

   

}

}

fun main

(

)

{

    println

(

parseAge

(

"18"

)

)

    println

(

parseAge

(

"runoob"

)

)

   

// The return value of the finally block is ignored and does not affect the result of the try expression

    val age

=

try

{

       

"20"

.

toInt

(

)

   

}

finally

{

        println

(

"The finally block executed but does not affect the value of try"

)

   

}

    println

(

age

)

}



18

-1

finally 块执行了,但不影响 try 的值

20

Note:Do not write return inside a finally block. It discards the return values from try and catch and also swallows exceptions being propagated, making it an error-prone pattern.


throw and Nothing

Using throw To throw an exception deliberately; the expression itself never has a return value, so its type is Nothing。

Nothing is a subtype of all Kotlin types, indicating "normal return is impossible here"; the compiler uses this for control-flow analysis.

Example

// A return type of Nothing means this function never returns normally

fun fail

(

message

:

String

)

:

Nothing

{

   

throw

IllegalArgumentException

(

message

)

}

fun checkAge

(

age

:

Int

)

:

String

{

   

// Because fail returns Nothing, the compiler knows execution does not continue past this point

   

if

(

age

<

0

)

fail

(

"Age cannot be negative: $age"

)

   

return

"Age is valid: $age"

}

fun main

(

)

{

    println

(

checkAge

(

18

)

)

   

try

{

        checkAge

(

1

)

   

}

catch

(

e

:

IllegalArgumentException

)

{

        println

(

"Caught exception: ${e.message}"

)

   

}

}



年龄合法:18

捕获到异常:年龄不能为负数:-1

In the standard library, the error()、TODO() and throw expressions all have a return type of Nothing; their purpose is to tell the compiler that "execution cannot continue".


Custom exceptions

When built-in exceptions cannot express business semantics, you can extend Exception to define your own exception type.

Store the context of the error as properties so that more information is available when catching it.

Example

// Custom exceptions usually extend Exception; keep the specific failing field as a property

class

InvalidSiteNameException

(

val siteName

:

String

)

:

Exception

(

"Illegal site name: $siteName"

)

fun registerSite

(

name

:

String

)

{

   

// The site name must start with runoob (case-insensitive), otherwise throw a custom exception

   

if

(

!

name.

startsWith

(

"runoob"

, ignoreCase

=

true

)

)

{

       

throw

InvalidSiteNameException

(

name

)

   

}

    println

(

"Registration successful: $name"

)

}

fun main

(

)

{

    registerSite

(

"runoob"

)

   

try

{

        registerSite

(

"example"

)

   

}

catch

(

e

:

InvalidSiteNameException

)

{

       

// e.siteName is the context information carried by the custom exception

        println

(

"Registration failed: ${e.message}, problem field: ${e.siteName}"

)

   

}

}



注册成功:runoob

注册失败:非法的站点名称:example,问题字段:example

By convention, name it with a Exception suffix and keep a constructor that accepts a message and cause so the exception chain can be propagated upward.


Kotlin has no checked exceptions

Java divides exceptions into checked and unchecked; checked exceptions must be explicitly try-catch'd or declared with throws in the method signature.

Kotlin removes this distinction; all exceptions are unchecked, and the compiler does not force you to handle them.

Comparison Item Java Kotlin
Exception classification Checked + unchecked exceptions Only unchecked exceptions
Method Declaration Checked exceptions require throws No declaration needed
Caller's obligation The compiler forces checked exceptions to be handled The compiler does not force it; you decide
Interoperability with Java Not applicable Using @Throws Inform Java callers

Example

import

java.io.IOException

// @Throws is only needed when Java callers must catch; on the Kotlin side it makes no difference

@

Throws

(

IOException

::

class

)

fun readConfig

(

path

:

String

)

:

String

{

   

if

(

path.

isEmpty

(

)

)

throw

IOException

(

"Configuration path is empty"

)

   

return

"Configuration comes from $path"

}

fun main

(

)

{

   

// Kotlin does not force try-catch, but exceptions are still thrown at runtime

    println

(

readConfig

(

"runoob.conf"

)

)

   

try

{

        readConfig

(

""

)

   

}

catch

(

e

:

IOException

)

{

        println

(

"Read failed: ${e.message}"

)

   

}

}



配置来自 runoob.conf

读取失败:配置路径为空

Note:Removing checked exceptions does not mean you can ignore exception handling. Kotlin gives the decision of whether to handle back to the developer, at the cost that a missing catch is only discovered at runtime.


use and automatic resource closing

Resources such as files, streams, and database connections must be closed after use, otherwise handles will leak.

Kotlin uses the extension function use to replace Java's try-with-resources; whether or not an exception is thrown in the block, it calls close()。

Example

import

java.io.File

fun main

(

)

{

   

// use automatically calls close() after the block ends, even if an exception was thrown inside

   

File

(

"runoob.txt"

)

.

bufferedWriter

(

)

.

use

{

writer

->

        writer.

write

(

"Hello RUNOOB"

)

        writer.

newLine

(

)

                 

// Write a newline

        writer.

write

(

"Hello Kotlin"

)

   

}

   

// Read back the content just written

   

File

(

"runoob.txt"

)

.

bufferedReader

(

)

.

use

{

reader

->

        reader.

forEachLine

{

line

->

println

(

line

)

}

   

}

   

// useLines reads all lines at once and closes the file automatically after the block

   

File

(

"runoob.txt"

)

.

useLines

{

lines

->

        println

(

"Total lines: ${lines.count()}"

)

   

}

}



Hello RUNOOB

Hello Kotlin

总行数:2

use Applies to all objects that implement Closeable or AutoCloseable ; the return value is the result of the last expression in the block, so you can also write it like this:

The following example reuses the runoob.txt generated by the previous example. Please run the previous code first, or make sure this file already exists in the current directory.

Example

import

java.io.File

fun main

(

)

{

   

// The return value of use is the last line inside the block; here we get the line count of the file

    val lineCount

:

Int

=

File

(

"runoob.txt"

)

.

useLines

{

lines

->

lines.

count

(

)

}

    println

(

"The file has $lineCount lines"

)

}



文件共有 2 行


runCatching

runCatching Combines "execute + catch" into a single expression, wrapping both success and failure into a Result Result object.

Suitable for scenarios where "failure is a normal branch", such as parsing user input or reading configuration that may not exist.

Method Purpose
isSuccess / isFailure Check whether the result is success or failure
getOrNull Return the value on success, null on failure
getOrDefault Return a specified default value on failure
getOrElse Use the exception to compute a fallback value on failure
getOrThrow Re-throw the exception on failure
onSuccess / onFailure Perform a side effect on success or failure and return the original Result

Example

fun main

(

)

{

   

// Both success and failure are wrapped into a Result and do not interrupt the program

    val ok

=

runCatching

{

"42"

.

toInt

(

)

}

    val bad

=

runCatching

{

"runoob"

.

toInt

(

)

}

    println

(

"Success: isSuccess=${ok.isSuccess}, value=${ok.getOrNull()}"

)

    println

(

"Failure: isFailure=${bad.isFailure}, value=${bad.getOrNull()}"

)

    println

(

"Default value on failure: ${bad.getOrDefault(-1)}"

)

   

// getOrElse receives the exception, so a fallback value can be built from it

    val fallback

=

bad.

getOrElse

{

e

->

"Fallback(${e.message})"

}

    println

(

"Fallback result: $fallback"

)

   

// onFailure is suitable for logging and does not affect the subsequent flow

    runCatching

{

"x"

.

toInt

(

)

}

        .

onFailure

{

println

(

"onFailure:${it.javaClass.simpleName}"

)

}

}



成功:isSuccess=true,值=42

失败:isFailure=true,值=null

失败时给默认值:-1

兜底结果:兜底(For input string: "runoob")

onFailure:NumberFormatException

runCatching Available since Kotlin 1.3; the Result type it returns became stable in 1.5.

Note:runCatching catches Throwable, which also swallows a coroutine's CancellationException and prevents the coroutine from being cancelled normally. When using it in a coroutine, either switch to try-catch that catches only specific exceptions, or re-throw CancellationException in the failure branch.


Common questions

The following summarizes the most common questions about exception handling.

Problem Reason Recommendation
The catch branch does not take effect A supertype was written before a subtype and got matched first Write the more specific exception type first
Caught an exception but cannot locate the problem Only the message was printed and the stack trace was lost Using e.printStackTrace() or a logging framework to record the full exception
A return in finally causes an unexpected result The return value of finally overrides the result of try Use finally only for cleanup and do not write return
Resource not closed Forgot to call close in finally Switch uniformly to use or useLines
Catch scope too broad Catching Throwable or Exception directly Catch specific types where possible so unexpected exceptions surface normally