An exception is an unexpected error that occurs at run time and leads to the termination of the program execution.
There are two types of exceptions in general.
We only have unchecked exceptions in Kotlin. All exception classes inherit the Throwable
class.
Let's see an example of an ArithmeticException
in Kotlin in the following code snippet.
fun main() {// dividing by zero will throw an arithmetic exceptionvar n = 1/0println("n = $n")}
In the code snippet above:
ArithmeticException
by dividing a number by zero. Upon execution of the program, the exception is thrown and the program gets terminated.Exception handling is a mechanism by which we can handle unchecked exceptions and stop the termination of program execution due to them.
An exception can be handled using the try-catch
block. All the executable code is written inside the try
block. In case an exception occurs, the try
block will throw that exception. The exception thrown by try
block is captured by the catch
block, where the exception is actually handled.
Note: Atry
block should be immediately followed by acatch
block.
try {// code that can throw a exception} catch (e: Exception) {// handle the exception}
Let's see an example of ArithmeticException
handling in Kotlin using try-catch
, in the following code snippet.
fun main() {try {// dividing by zero will throw an arithmetic exceptionvar n = 1/0println("n = $n")} catch (e: ArithmeticException) {println("Cannot perform 'Divide by Zero'")}}
In the code snippet above:
try
block.ArithmeticException
is thrown by try
block and handled in the catch
block. Cannot perform 'Divide by Zero'
is printed on the console. Here, the program execution does not get terminated.catch
block to handle the ArithmeticException
.