Kotlin code provides handling exceptions using try, catch, and finally. It is similar to the Java language

Normally, if Program execution throws any error at runtime, It Stops the program execution gracefully.

For Example, the Calling Function either returns successful execution or an exception if the error is thrown. The caller needs to handle the exception or propagate the exception to the calling hierarchy

The exception is nothing but an error, contains Message, StackTrace, and an optional clause

There are two types of exceptions in General in other programming languages.

  • Compile time exceptions: alias Checked Exceptions throws at compile time
  • Runtime Exceptions: alias unchecked exceptions thrown at runtime.

There is no difference between compile and runtime in Kotlin

Kotlin exception handling example

Kotlin provides try with catch and finally to handle exceptions

try {
    //Some work
} catch (e: Exception) {
    // handler
} finally {
    // optional finally block for clean up
}

try is an expression in Kotlin, catch handles the exception, executes code, and converts it to a successful result, if any code inside try throws an error finally always executes whether an exception is thrown or not

Here is an example

 fun main(args: Array<String>) {
     try {
     throw Exception("Custom Exception")
} catch (e: Exception) {
     println("catch");

    println(e);
     } finally {
    println("finally");
}
}

Output:

catch
java.lang.Exception: Custom Exception
finally

How to catch many exceptions at the same time in Kotlin?

You can handle multiple exceptions in Kotli using multiple catch blocks The below example contains a catch block for each Exception type.

try{
    // code
} catch(e: Exception1){
    // handle exception1
} catch(e: Exception2){
    // handle exception2
} catch(e: Exception3){
    // handle exception3
}

Exception Class in Kotlin

Each Exception in Kotlin extends the Throwable class.

Throwable is a superclass that extends every Built-in or custom exception.

It contains a message and stack trace.

How to create and throw a Custom Exception in Kotlin

Custom Exceptions are user-defined exceptions that can be created by Extending the Exception or Throwable Class

  • First, Create a class MyException by extending Exception and override all four constructors. Below calls the superclass constructor for all this.
class MyException: Exception {
    constructor() : super()
    constructor(message: String) : super(message)
    constructor(message: String, cause: Throwable) : super(message, cause)
    constructor(cause: Throwable) : super(cause)
}

or
class MyException : Throwable {
    constructor() : super()
    constructor(message: String) : super(message)
    constructor(message: String, cause: Throwable) : super(message, cause)
    constructor(cause: Throwable) : super(cause)
}
  • After Custom Exception is Created, You need to throw in code, throw takes an expression and returns type Nothing. Nothing does not return, the code completed its execution and is marked as nothing

Exceptions are thrown using the throw keyword as given below

 fun main(args: Array<String>) {
     throw MyException("Custom Exception")
 }

Output:

Exception in thread "main" MyException: Custom Exception
 at FileKt.main (File.kt:2)
 at jdk.internal.reflect.NativeMethodAccessorImpl.invoke0 (:-2)
 at jdk.internal.reflect.NativeMethodAccessorImpl.invoke (:-1)