![]() |
VOOZH | about |
Exceptions are the error which comes at the runtime and disrupts your flow of execution of the program. Basically exception is the unwanted event that occurs at runtime. The method by which we can handle this kind of error is called Exception Handling.
Note: In Kotlin we have only unchecked Exceptions which only figure out at the runtime.
We have some keywords which help us to handle Exceptions.
- Try // This will try to find the exception
- Throw // If exception found then it will throw the exception
- Catch // After throwing it will catch the exception and execute their body.
We have one more keyword called Finally, It will always execute either we got exception or not. In this, we have some important codes that always need to execute.
Note: If the program exit by exitProcess(Int) or abort(), then the finally will not be executed.
Example 1: Divide By Zero
Output:
Divide by zero
Example 2: Let's try the same code with try-catch and finally.
Output:
Division is : 2 I'm executed Divide by zero I'm executed
Note that In the above example, finally is executed in both cases either exception occurs or not.