Exception Handling - Kotlin

An exception is an undesired or unexpected event that arises during programme execution, or run time, that interferes with the regular flow of the instructions in the programme . Exception handling is a method by which we may manage mistakes and avert programme crashes that could occur during runtime.

There are two type of exceptions-

1. Checked Exception - This exception come from while code in run time like IOException.

2. UnChecked Exception - This exception come from run time like NullPointerException,etc

Common exception  mentioned below

  • NullPointerException: when object is null then execute this Exception.
  • ArithmeticException: when any digit divide by zero then execute this exception
  • SecurityException: it is thrown to indicate security violation.
  • ArrayIndexOutofBoundException: it is throw when array of bound exception.

Exception of arrayIndexoutofboundException :

 fun main(args : Array<String>){
   var num = 50 / 0
   println(num)
 }

Output

 Exception in thread "main" java.lang.ArithmeticException:/ by  zero
 at FileKt.main (File.kt:3)
 at jdk.internal.reflect.NativeMethodAccessorImpl.invoke0 (:-2)
 at jdk.internal.reflect.NativeMethodAccessorImpl.invoke (:-1)

Kotlin try-catch block-

In Kotlin, we used a try-catch block for exception handling in the program, try block writing the code, and then throwing exceptions while in the catch block.  

Syntax

 try {
   // code that can throw exception
 } catch(e: ExceptionName) {
   // catch the exception 
 }


  •  ArithmeticException
  fun main(args : Array<String>){ 
try{
var num = 70 / 0
}
catch(e: ArithmeticException){

println("Divide by zero not allowed")
}
}

Output 

 Divide by zero not allowed
  •  Finally block
 un main(args : Array<String>){ 
try{
var ar = arrayOf(1,3,3,4,5)
var int = ar[7]
println(int)
}
finally {
println("This block always executes")
}
}

Happy coding!

  

365Bloggy July 12, 2024
Share this post
Tags
SUBSCRIBE THIS FORM


Archive