How to do Exception Handling in Kotlin?

 An Exception in Kotlin is a runtime Exception. The process by which Exceptions are handled is called Exception Handling.
The following keywords need to be understood and used in Programming.

Here is a simple example that handles conversion from a String to Int.

fun main(args:Array<String>)

{

    try

    {

      var x:Int=  "10".toInt()

        println(x)

    }

    catch(ex:Exception)

    {

        println(ex)

    }

}

Varanasi Software Junction: Kotlin Exception Handling

Run this program after changing the String to be converted.


We can have separate Exception Handling blocks for different Exception types.



fun main(args:Array<String>)
{
    try
    {
      var x:Int=  "10".toInt()
        println(x)
        var y:Int=9
        x=x/y
         var arr:Array<String>
         arr=Array(5,{""})
         println(arr[1])
       

    }
    catch(ex:ArithmeticException)
    {
        println("Arithmetic Exception")
        println(ex)
    }
    catch(ex:NumberFormatException)
    {
        println("Number Format Exception")
        println(ex)
    }
    catch(ex:Exception)
    {
        println("Unknown Exception")
        println(ex)
    }
    finally {

            println("Finally")


    }
}
 

Varanasi Software Junction: Kotlin Exception Handling

Change the code to create exceptions and see the results

var x:Int=  "bnbvnbv".toInt()

Varanasi Software Junction: Kotlin Exception Handling



Throwing an exception from a function

fun main(args:Array<String>)
{
println(factorial(-10))
}
@Throws(Exception::class)
fun factorial(n:Int):Int
{
if (n<0)
    throw Exception("-ve numbers not allowed")
    var prod:Int =1
    var i:Int
    for(i in 2..n)
        prod=prod*i
    return prod
}
Varanasi Software Junction: Kotlin Exception Handling

Program to create our own exception

class MyException:Exception
{
    constructor(message:String) : super(message)
    {
println("Super Class Constructor with message " + message)
    }
    constructor():super()
    {
        println("Super Class Constructor")
    }
}

fun main(args:Array<String>)
{
    try
    {
      var x:Int=  "10".toInt()
       if(x==10)
           throw MyException("10 not allowed")

    }
    catch(ex:ArithmeticException)
    {
        println("Arithmetic Exception")
        println(ex)
    }
    catch(ex:NumberFormatException)
    {
        println("Number Format Exception")
        println(ex)
    }
    catch(ex:Exception)
    {
        println("Unknown Exception")
        println(ex)
    }
    finally {

            println("Finally")


    }
}

Varanasi Software Junction: Kotlin Exception Handling







Post a Comment

0 Comments

Me