Exception Handling in Kotlin with examples..

Satheesh Guduri
2 min readFeb 13, 2021

--

In this article, we will what is the Exception and how to handle it.

Exception:

After writing the code first you have to compiling it, then executing the code right? while compiling if you are getting any errors are nothing but compile time errors and while executing the code if you get the errors are nothing but runtime errors or exceptions.

For example, if you are dividing any number by zero the compiler wont give any error but in the run time you will get the Arithmatic Exception, it means app will crash.

One more example, you have list with 3 items, [“apple”, “mango”,”banana”] and if you accesing the 4 th item you will get Index out of range exception will come.

How to Handle:

To handle the exception we use try and catch blocks.

Here we put the code in try block, when exception occurs the try block throws the exception to catch block and catch will decide which exception it is. Here we have two catch blocks one is Arithmetic and Second one is Exception, if we dont know exactly which exception we are going to get then we use Exception class.

Here if you observe, in the try block we have two statements but when error occurs the second statement won’t execute. In some cases, either exception occurs or not we need to execute some code then we use finally block like below image.

Throw Your Own Exception:

When you are dividing a number by zero the system is throwing the exception in sameway we can also throw our custom exceptions.

See the above image, here if a value is greater than 5 then we are throwing an error that is nothing but custom exception.

Thanks for reading, if you like this article please applaud.

--

--

Satheesh Guduri
Satheesh Guduri

Written by Satheesh Guduri

Mobile App Developer and Trainer

No responses yet