Throw Custom Exception in Kotlin


Exception is an important aspect of any programming language. It prevents our code from generating incorrect output at runtime.

The concept of exception in Kotlin is very much same as it is in Java. All the exceptions in Kotlin are the descendants of Throwable class. In Kotlin, developers do have the privilege to create their own custom Exception.

Custom Exceptions are a part of unchecked exceptions which means they will be thrown at the runtime.

Before getting into custom exceptions in Kotlin, let's take a look checked and unchecked exceptions.

Checked Exceptions

Checked exceptions are those which are checked at the compile time. In the following example, we have generated a checked exception. FileNotFoundException or IOException is a checked exception.

Example

import java.io.File
import java.io.InputStream

fun main(args: Array<String>) {
   try {
      val inputStream: InputStream = File("Hello.txt").inputStream()
   }
   catch(e:Exception) {
      e.printStackTrace();
   }
}

Output

Once you execute above piece of code, it will generate the following output. You could see that while compiling, we have got the checked exception as an output.

$kotlinc -nowarn main.kt -include-runtime -d main.jar
$java -Xmx128M -Xms16M -jar main.jar
java.io.FileNotFoundException: Hello.txt (No such file or directory)
   at java.io.FileInputStream.open0(Native Method)
   at java.io.FileInputStream.open(FileInputStream.java:195)
   at java.io.FileInputStream.(FileInputStream.java:138)
   at MainKt.main(main.kt:6)

Unchecked Exceptions

Unchecked exceptions are those which are not checked at the compile time; rather they will be thrown at runtime. In the following example, we will generate an Unchecked Exception. We can consider any of the ArithmeticException, NumberFormatException as examples of unchecked exceptions.

Example

fun main(args: Array) {
   try {
      val myVar:Int = 12;
      val v:String = "Tutorialspoint.com";
      v.toInt();
   }
   catch(e:Exception) {
      e.printStackTrace();
   }
   finally {
      println("Exception Handeling in Kotlin");
   }
}

Output

Once we execute the above piece of code, it will produce the following output −

$kotlinc -nowarn main.kt -include-runtime -d main.jar
$java -Xmx128M -Xms16M -jar main.jar
Exception Handeling in Kotlin
java.lang.NumberFormatException: For input string: "Tutorialspoint.com"
   at java.lang.NumberFormatException.forInputString(NumberFormatExc eption.java:65)
   at java.lang.Integer.parseInt(Integer.java:580)
   at java.lang.Integer.parseInt(Integer.java:615)
   at MainKt.main(main.kt:5)

Custom Exception in Kotlin

We will create our own custom exception using a very simple example. In this example, we are declaring a variable and checking whether that variable value is less than 50. Depending on the outcome, we will throw a custom exception using Kotlin built-in functionality.

Example

fun main(args: Array) {
   val sampleNumber:Int;
   sampleNumber = 100;
   if(sampleNumber > 50)
   {
      //throwing custom exception instead of other checked Exception
      throw myCustomException("Invalid Inputs - Please enter a correct number")
   }

   else
   {
      println("Welcome !! you have entered a correct value")
   }
}

//declaring custom exception class
class myCustomException(message: String) : Exception(message)

Output

When we execute this code, it will yield the following output. You can observe that we are throwing our custom exception along with the passed message.

$kotlinc -nowarn main.kt -include-runtime -d main.jar
$java -Xmx128M -Xms16M -jar main.jar

Exception in thread "main" myCustomException: Invalid Inputs -
Please enter a correct number
at MainKt.main(main.kt:7)

Updated on: 27-Oct-2021

796 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements