try catch

5 0 0
                                        

try catch uses exceptions. Exception is an error but an anticipated error. It is like dividing a number by a zero. So, as a programmer, you already know that dividing by zero is not possible. So, you use an Exception to make sure your program can catch it and will do something about it as to keep your program running.

syntax:

try{

}catch(e: Exception){

}finally{

}

Note: block is a body of statements that is within the braces.

1. try block is where you put your program to run. Also, this is where you put your throw. throw is a keyword used to throw an exception because what is there to catch if you did not throw anything. throw comes a Throwable class that is defined in your API.

     throw Exception("your message");

2. catch block - this is the program that runs when there is some error in your code. You can do other things besides catching an error. And take note that you can put one or more catch exceptions after the try. The Exception class is the general exception where it catches any error but for specific exception, see the documents for that like IndexOutBoundsException when you exceed your array size.

3. finally block - this is where you close those objects that are so expensive when creating like opening a File to access for example a document. This block will always run after the try block whether that try block has an error or none.

==================

fun main(){

    try{

        val scanner: Scanner = Scanner(System.'in')

        val array: Array<Int> = Array(2){it * 1}

        var counter = 0

        while(counter < array.size){

            array[counter] = scanner.nextInt()

            counter++

        }

        if(array[1] == 0){

            throw Exception("Cannot divide a zero")

        }else {

            val answer = array[0]/array[1]

           println("answer: $answer")

        }

        scanner.close()

    }catch(e: Exception){

        System.err.println(e.localizedMessage())

    }finally{

        println("There is nothing to close for now.")

    }

}

==================

Result:

23

0

Cannot divide a zero

There is nothing to close for now.


Note: The underlined result is the number you input, since array[1] = 0, then it throws an exception. In the catch block, we printed the localized message which is the message we received in the throw. Also take note of the finally block, it still runs.

try catch can be an expression too which means that the last value of either the try or the catch is the return value. The finally is not included for the return of the value.

======================

fun main(){

    val answer = try{

        val scanner = Scanner(System.'in')

        val array = Array(2){it * 1}

        var counter = 0

        while(counter < array.size){

            print("Enter a number: ")

            array[counter] = scanner.nextInt()

            counter++

        }

        if(array[1] == 0){

            throw Exception("Cannot divide to a zero")

        }else {

            array[0] / array[1]

        }

    }catch(e: Exception){

        System.err.println(e.localizedMessage())

        null

    }finally{

        println("There is nothing to close here")

    }

}

======================

Result:

Enter a number: 32

Enter a number: 2

There is nothing to close for now

answer: 16


Note: 

1. Kotlin does not have  checked exceptions. I don't know what this means yet but it says here that checked exceptions are good for small programs but when it comes to large programs it becomes a headache. So, kotlin did not incorporate checked exceptions.

2. Nothing? has one possible value which is null. And throw when use as in an expression has a type Nothing. So you can use the throw in an elvis operator. The elvis operator ?: is use like a ternary operator except the condition is automatically checked if it is null and the value when false is automatically null.

sample:

val scanner = Scanner(System.'in')

val name = scanner.nextInt() ?: throw IllegalArgumentExceptions("the value is null")

In this sample, if the input type is null, it will throw an exception if not it will assign the value to the variable name.

3. You can use Nothing as a return type for functions that does not need to return.

sample:

fun errorMessage(message: String): Nothing{

    throw Exception(message)

}

Kotlin ProgrammingWhere stories live. Discover now