Kotlin try catch Block Tutorial With Example

Greetings!
We have recently published 100+ articles on android tutorials with kotlin and java. If you need, you may visit Android Tutorial for beginners page. You can also check Kotlin Tutorial for beginners. Also, if you are interested in content writing, you can mail us at tutorialwing@gmail.com.

In this kotlin tutorial, we will learn how to use kotlin try catch block in any program? We will go through different examples of kotlin try catch block to boost up knowledge in handling exception in program. We will also see how to use kotlin try catch block as an expression in the program.

Getting Started

We use try catch block for exception handling in kotlin program. try block contains the code that are responsible for throwing exception. For example,
If there is any calculation in the program that can divide a number by 0, we enclose those lines within try block as below

try {
   var num = 10 / 0
}

Above line indicate that there is a possibility of error in the program (when such calculations will be carried out). So, we enclose it with try block and catch the possible exception using catch block.

Syntax of using kotlin try catch block
try {
   // write code here that can throw exception
} catch(e: ExceptionName) {
   // catch the exception handle it.
}
Syntax of using kotlin try block with finally block
try {
   // write code here that can throw exception
} finally {
   // perform some operation that you want to be performed when exception occurs. For example, releasing resources
}
Syntax of using kotlin finally block with try catch block
try {
   // write code here that can throw exception
} catch(e: ExceptionName) {
   // catch the exception handle it.
} finally {
  // perform some operation that you want to be performed when exception occurs. For example, releasing resources
}

Why do we handle exception in kotlin program?

As we already know when exception occurs, our program stops executing abruptly. Let’s take an example,

fun main(args: Array<String>) {
    val result = (200 / 0)
    print("Result = $result")
}

When you run this program, you will get exception in line val result = (200 / 0). So, program will stop executing abruptly. Thus, line below it won’t be executed.
Now, image a situation like below

fun main(args: Array<String>) {
    // Get access to some resources
    val result = (200 / 0)
    print("Result = $result")
    // Release resources
}

When you run the program, you will get output –
Exception in thread “main” java.lang.ArithmeticException: / by zero

In this case, val result = (200 / 0) will throw exception as a result program will stops executing.
Since line below it won’t be executed, resources accessed by this program won’t be released.
This is the main reason why we need to handle exception in kotlin program or in any other program.

Handle Exception in Kotlin Using try catch block

As we already know, we use try catch block to handle exception. Enclose the line(s) of code, that are responsible to throw exception, in try block.

try {
    val result = (200 / 0)
}

then, catch the exception using catch block

try {
    val result = (200 / 0)
} catch (e: ArithmeticException) {
   // Handle the exception. For example, write to show error in log, console etc.
}

Finally, our program will be like

fun main(args: Array<String>) {
    try {
        val result: Int = (200 / 0)  // This line may throw exception
        print("Result = $result")
    } catch (e: ArithmeticException) {
        print("Exception Occurred: Is you calculation correct?")
        // Handle the exception. For example, write to show error in log, console etc.
    }
}

When you run the program, you will get message:
Exception Occurred: Is you calculation correct?

Similarly, you can handle any exception in kotlin using try catch block.

Kotlin try catch block as an expression

We already know difference between kotlin expression, statement and block. An expression returns a value. We can use kotlin try catch block as an expression in program. The result of the expression will be either last expression of try block or last expression of catch block. If exception occurs, then, value returned will be last expression of catch block. Otherwise, it will be last expression of try block. Contents in finally block does not effect the result of the try catch expression. For example,

fun main(args: Array<String>) {
    val result =  try {
        val result: Int = 10  // This line may throw exception
        1
    } catch (e: ArithmeticException) {
        println("Exception Occurred: Is you calculation correct?")
        0
        // Handle the exception. For example, write to show error in log, console etc.
    }
    print("Got result: $result")
}

When you run the program, you will get output –
Got result: 1

Note that 1 is last expression of try block. Since there is no exception, last line was executed successfully and value 1 was returned.

Now, let’s see below example,

fun main(args: Array<String>) {
    val result =  try {
        val result: Int = (200 / 0)  // This line may throw exception
        1
    } catch (e: ArithmeticException) {
        println("Exception Occurred: Is your calculation correct?")
        0
        // Handle the exception. For example, write to show error in log, console etc.
    }
    print("Got result: $result")
}

When you run the program, you will get output –
Exception Occurred: Is your calculation correct?
Got result: 0

Note that 0 is last expression of catch block. Since there is an exception, because we are dividing a number by zero, last line of try block won’t be executed. Then, catch block will be executed and value of last line of catch block will be returned.

Exercises on Kotlin try catch block as an expression

1. Guess the output of below program

fun main(args: Array<String>) {
    val result =  try {
        val result: Int = 200 / 0  // This line may throw exception
        1
    } catch (e: ArithmeticException) {
        println("Exception Occurred: Is your calculation correct?")
        1 + 2
        // Handle the exception. For example, write to show error in log, console etc.
    } finally {
        9 + 10
    }
    print("Got result: $result")
}

2. Guess the output of below program

fun main(args: Array<String>) {
    val numb = getInt("100")
    println(numb)
}

fun getInt(s: String): Int {
    return try {
        Integer.parseInt(s)
    } catch (e: ArithmeticException) {
        0
    }
}

3. Guess the output of below program

fun main(args: Array<String>) {
    val numb = getInt("100s")
    println(numb)
}

fun getInt(s: String): Int {
    return try {
        Integer.parseInt(s)
    } catch (e: ArithmeticException) {
        0
    }
}

4. Guess the output of below program

fun main(args: Array<String>) {
    val numb = getInt("100s")
    println(numb)
}

fun getInt(s: String): Int {
    return try {
        Integer.parseInt(s)
    }
}

That’s end of tutorial on Kotlin try catch block.

Support Us

If you like Tutorialwing and would like to contribute, you can email an article on any educational topic at tutorialwing@gmail.com. We would love to publish your article. See your article on Tutorialwing and help others with your knowledge. Follow Facebook, LinkedIn, Google+, Twitter, Youtube for latest updates.
Greetings!
We have recently published 100+ articles on android tutorials with kotlin and java. If you need, you may visit Android Tutorial for beginners page. You can also check Kotlin Tutorial for beginners