Exception Handling in Kotlin
Kotlin Exception Handling
In this article, we will go through the following:
- What is an Exception?
- What is Exception Handling?
- Types of Exception in kotlin?
What is an Exception?
Exception in layman language means a halt in the execution due to some unwanted condition. Similarly, in the programming language, an exception means an unexpected error occurs during runtime and terminates the program. This may occur due to multiple reasons such as running out of memory, conditions like divide by zero, and more. To handle this type of error, we have the concept of exception handling.
What is Exception Handling?
It is a technique that handles the runtime problem and maintains the flow of the program. Throwable class is the top-notch class of all the exceptions. To throw an exception object, it uses a throw expression.
There are four keywords to handle the exception:
- try: try block contains the statements that may generate an exception to occur the problem in execution. It follows by a catch block or finally block or maybe both blocks.
- catch: It uses to catch the exception thrown by the try block.
- finally: This block always executes whether try throws an exception or not. It kind of always carry important statements to execute.
- throw: throw keyword is throws an exception explicitly.
As we know, the two types of exceptions exist in the programming language i.e. checked and unchecked exception.
Checked Exception | Unchecked Exception |
It is checked during compile time. | It is checked during runtime. |
It falls under the throwable class. | It falls under the RunTime Exception class |
The examples of the Unchecked Exceptions are:
- ArrayIndexOutOfBoundException: It gives an error when the user tries to access the incorrect index.
- NullPointerException: It gives an error when the user invokes the null object.
- ArithemeticException: It gives an exception when trying to divide any number by zero.