Kotlin exception handling - try, catch, finally, throw

2022. 5. 29. 17:33카테고리 없음

1. throw

throw (keyword) + name of the customized exception + (code to throw)

 

2. normal code

fun main() {
   val str = numberFunction("73")
   println(str)
}

fun numberFunction(str:String):Int{
    return Integer.parseInt(str)
}

The variable 'str' has string type, and it is parsed by the function 'numberFunction' to int.

Thus, the program prints '73'

 

3. error code

fun main() {
   val str = numberFunction("7.3")
   println(str)
}

fun numberFunction(str:String):Int{
    return Integer.parseInt(str)
}

The variable 'str' has string type, and it can not be parsed by the function 'numberFunction' to int.

That's because the input string is double, which occurs the format error of number (Number format exception).

Thus, the result of the program is here.

4. nested catch

fun main() {
   val str = num("7.2")

}

fun num(str: String):{
    println("The parced data is ${str}")
    var a = try{
        try {
            Integer.parceInt(str)
            println(str)
        }catch(e:ArithmeticException){
            println("c")
        }
    
    }catch(e:ArithmeticException){println("d")}

return a
}

5. finally

fun main() {
    try{
        val nameIntro= "Slowbook is my name"
        println(nameIntro)
    }catch(e:NullPointerException){
        println(e)
    }finally{
        println("always printed, unrelated to the error occurence")
    }
    }

 

 

6. throw

fun main() {
    var count =0
    
    //try, catch, finally
    try{
        val nameIntro= "Slowbook is my name"
        count++
        println(nameIntro)
    }catch(e:NullPointerException){
        println(e)
        count--
    }finally{
        count++
        println("always printed, unrelated to the error occurence")
    }
    
    //if, throw
    if(count==2){
        println("success")
    }
    else {
        throw ArithmeticException("under count")
    }
 }