Kotlin Exception Handling

An exception is an unwanted or unexpected event, which occurs during the execution of a program i.e at run time, that disrupts the normal flow of the program's instructions. Exception handling is a technique, using which we can handle errors and prevent run time crashes that can stop our program.

There are two types of exceptions
  • Checked exceptions that are declared as part of method signature and are checked at the compile time, for example IOException
  • Unchecked exceptions do not need to be added as part of method signature and they are checked at the runtime, for example NullPointerException.

Note: In Kotlin all exceptions are unchecked.

Kotlin Exceptions

All Exceptions descend from the Throwable class. To throw an exception we use the throw keyword.

throw Exception("Oops. Something went wrong")

Note: In Kotlin there are no checked exceptions. That means there is no throws keyword.


Some of the common exceptions are:
  • NullPointerException: It is thrown when we try to invoke a property or method on null object.
  • ArithmeticException: It is thrown when invalid arithmetic operations are performed on numbers.
  • SecurityException: It is thrown to indicate security violation.
  • ArrayIndexOutOfBoundException: It is thrown when we try to access invalid index value of an array.