Kotlin Exception handling
An exception is a runtime problem that occurs in the program and leads to program termination. This may occur due to running out of memory space, array out of bond, and conditions like divided by zero. To handle this type of problem during program execution the technique of exception handling is used.
Exception handling is a technique that handles runtime problems and maintains the flow of program execution.
There are four different keywords used in exception handling. These are:
- try: try block contains a set of statements white might generate an exception. It must be followed by either catch or finally or both.
- catch: catch block is used to catch the exception thrown from the try block.
- finally: finally block always execute whether an exception is handled or not. So it is used to execute important code statements.
- throw: throw keyword is used to throw an exception explicitly.
Kotlin Unchecked Exception
An unchecked exception is that exception that is thrown due to mistakes in our code. This exception type extends the exceptions class. The Unchecked exception is checked at run time. Following are some examples of unchecked exceptions:
- ArithmeticException: thrown when we divide a number by zero.
- ArrayIndexOutOfBoundExceptions: thrown when an array has been tried to access with an incorrect index value.
- SecurityException: thrown by the security manager to indicate a security violation.
- NullPointerException: thrown when invoking a method or property on a null object.
Multiple catch Block:
try {
val a = IntArray(5)
a[5] = 10 / 0
} catch (e: ArithmeticException) {
println("arithmetic exception catch")
} catch (e: ArrayIndexOutOfBoundsException) {
println("array index outofbounds exception")
} catch (e: Exception) {
println("parent exception class")
}
Note: At a time only one exception occurs and at a time only one catch block is executed.Nested try-catch block:
val nume = intArrayOf(4, 8, 16, 32, 64, 128, 256, 512)
val deno = intArrayOf(2, 0, 4, 4, 0, 8)
try {
for (i in nume.indices) {
try {
println(nume[i].toString() + " / " + deno[i] + " is " + nume[i] / deno[i])
} catch (exc: ArithmeticException) {
println("Can't divided by Zero!")
}
}
} catch (exc: ArrayIndexOutOfBoundsException) {
println("Element not found.")
}
Output:
4 / 2 is 2
Can't divided by Zero!
16 / 4 is 4
32 / 4 is 8
Can't divided by Zero!
128 / 8 is 16
Element not found.
finally Block:
try {
val data = 10 / 5
println(data)
} catch (e: NullPointerException) {
println(e)
} finally {
println("finally block always executes")
}
throw keyword:
fun main(args: Array<String>) {
validate(15)
println("code after validation check...")
}
fun validate(age: Int) {
if (age < 18)
throw ArithmeticException("under age")
else
println("eligible for drive")
}
Output:
Exception in thread "main" java.lang.ArithmeticException: under age
Comments
Post a Comment