Kotlin Exception Handling
Exception are unreliable situation that are produce wrong result and terminate program abnormally. All modern programming language are provide a mechanism to handle the unwanted condition that are produced exception in during program execution. This process is called exception handling. This exception is occur during program execution, so that is very dangerous. The main reason of exception are occured logical error and system failure situation.
So programmer are responsible to handle logic system failures condition, Provide a better mechanism to overcome exception situation And continue the execution flow of program. In this post we are learning about how to control exception condition in kotlin programming.
Exception Control Mechanism
Kotlin is provide exception handling mechanism in similar to Java Programming. there are use try, throw, catch and finally block are used to handle exception situation.
try {
//The code that can produce runtime exception
}
catch (e: SomeException) {
// handler
}
catch (e: OtherException) {
// handler
}
finally {
// optional finally block
}
try: We are written all statement in try block which can be produced an exception of run time. When exception is occured then automatically executing the relative catch block statements.
throw:This are used to throw custom exception, That is provide an reliable environment to produce on exception to deal with specified condition.
For example value are divisible by zero is produce an exception like (java.lang.ArithmeticException). In this situation we can handle this problem in two ways
Check before divide , divisor is zero or not. If that is zero then not divide. And other way we can handle this situation to by using throw the exception ArithmeticException. And make a on custom handling mechanism, See this example in next section how to create custom exception in Kotlin Programming.
catch: This block are work when exception is occurred during program execution. This block can be single or multiple in single try block. Because single try block are can be producing multiple exception.
finally: That is optional, this are always execute when exception is occurred or may not.
Exceptions Situation
There is many situations are possible to produced by your code an exceptions. Here given few situations. For example, when not providing a valid input for variable value during program execution. Then compiler are producing an exception.
fun main(args: Array<String>) {
var number:Int //define a variable
println("Enter a number")
try{
number = readLine()!!.toInt() //input integer values
println("Your are put number : $number")
}catch(e: NumberFormatException){
//When not a valid integer value
println("Error : $e")
//Set number to 0
number=0
}finally{
println("End of program execution")
}
}
Output
Enter a number
o
Error : java.lang.NumberFormatException: For input string: "o"
End of program execution
In above program when not put valid integer then this situation are produced exception and compiler are throw this exception, so we are catch this execution by catch block by using of exception type. This process are handling abnormal termination condition and provide valid message.
In case we are provide a valid value then this mechanism are not work, but finally block is always execute when exception is occurred or not. So We can be removing finally statement, if we are not need to this statement.
Arithmetic Exception : When divide any number by zero compiler are break program execution. We can handle this exception in this way.
fun main(args: Array<String>) {
try {
var a = 0
var b = (60 / a) //Divisible by zero
print("Everything is Good ( a : $a , b : $b )")
} catch (e: ArithmeticException) {
println("Arithmetic Exception occurred")
} catch (e: Exception) {
println("Exception occured")
} finally {
println("Finally Block")
}
}
Output
Arithmetic Exception occurred
Finally Block
throw custom exception : We can throw custom exception when something wrong in logical calculation.
fun main(args: Array<String>) {
try {
var amount=1000000
if(amount>20000){
throw Exception(" You cannot withdraw amount of more than 20000 ")
}
} catch (e: ArithmeticException) {
println("Arithmetic Exception occurred")
} catch (e: Exception) {
println("Exception occured : ${e.message}")
} finally {
println("Finally Block")
}
}
Output
Exception occured : You cannot withdraw amount of more than 20000
Finally Block
Create Custom Exception in Kotlin
That is very easy to create custom class to provide exception message of custom exception. We are create a class, and this class are extend the properties of kotlin Exception class.
class MyException(message):Exception(message)
For example
//Make a custom class to display exception message
class InvalidPositiveNumber(message: String) : Exception(message)
fun main(args: Array<String>) {
var yourAge:Int
try{
//input age
println("Enter Your age: ")
yourAge=readLine()!!.toInt() //for accept integer values
if(yourAge<0){
//invalid age
throw InvalidPositiveNumber("Invalid age : $yourAge ")
}
println("Age: $yourAge")
}catch(e:InvalidPositiveNumber){
//Catch custome exception
//When not provide valid positive input
println("Error ${e.message}")
}
catch(e:NumberFormatException){
//When not provide valid integer input
println("Error: ${e.message}")
}
finally{
println("Executed Final block")
}
}
Output
Enter Your age:
-9
Error Invalid age : -9
Executed Final block
This custom execution controller mechanism are useful to handle logical errors.
Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.
New Comment