Both try and catch blocks in Kotlin are used to handle the exceptions. Handling the exceptions is an important part of any software development. Exception handling enables our code to continue running even if an exception occurs. In this tutorial on Kotlin try-catch, we will be learning about all the topics related to try and catch blocks with the help of examples.

Here's How to Land a Top Software Developer Job

Full Stack Developer - MERN StackExplore Program
Here's How to Land a Top Software Developer Job

Why Use Kotlin Try and Catch Expression?

In programming and development, there are times when a certain unexpected situation arises. To deal with these unexpected situations, we use try-catch expressions. An exception in Kotlin is an event that causes the program's usual flow to be disrupted. It can be defined as an object that JVM throws at runtime whenever a circumstance like this develops.

The try-catch blocks help to deal with these unwanted exceptions that disturb the normal flow of execution.

So now, let us understand what a Try block in Kotlin is.  

Try Block in Kotlin

Try block can be defined as a block of statements that may throw an exception when a specific type of exception occurs. The code which has a chance of raising an exception is put inside the try block. The try block is often followed by one or more than one catch blocks.

The syntax of try block is 

Kotlin_Try_Catch_1.

Now let’s understand the Catch block.

Catch Block in Kotlin

Whenever there is an exception in the try block, the corresponding catch block handles that particular exception. The try block throws the code which raises the exception, and that particular code is caught using the catch block. The catch block is responsible for storing code that takes counter-measures to manage the exception.

Kotlin_Try_Catch_2

Let's take a look at a try-catch block in action.

Kotlin_Try_Catch_3

In the example, we are trying to divide a number by 0. Here, this code generates an exception. To handle this code, we have put the code inside the try block. The catch block catches the exception and executes the instructions inside it.

The catch block is skipped if none of the statements in the try block throw an exception.

Now moving to try and catch block as an expression.

Try and Catch Block as an Expression

A set of values, variables, operators, and functions are referred to as an expression that work together to produce another value. As a result, the try-catch block can be used as an expression in Kotlin.

Furthermore, the try-catch expression's return value is the last expression of either the try or catch blocks, or The try and catch block's last statements are considered as return value. The value of the catch block is returned in the event of an exception. 

Now let us understand the next topic of Kotlin try-catch.

Learn the Ins & Outs of Software Development

Caltech Coding BootcampExplore Program
Learn the Ins & Outs of Software Development

Multiple Catch Blocks in Kotlin

In Kotlin, we can combine several catch blocks with the try block. This is especially important if we do numerous types of actions in the try block, which raises the chances of catching multiple exceptions.

Syntax:

try {

    // Code which may throw multiple exceptions

}

catch (exception: ExceptionType1){

    // Handling exception

}

catch (exception: ExceptionType2){

    // Handling exception

}

catch (exception: ExceptionType3){

    // Handling exception

}

Let's take a look at a Multiple catch block in action.

Kotlin_Try_Catch_4

In this example, as we can see, there's a variable num that is storing a value of 60/0. The exception that occurred here is an Arithmetic exception; however, the first two catch blocks didn’t handle the Arithmetic exception, that's why the third catch block’s code executed. 

Let's move on to the next Kotlin try-catch topic.

Here's How to Land a Top Software Developer Job

Full Stack Developer - MERN StackExplore Program
Here's How to Land a Top Software Developer Job

Nested Try-Catch Block In Kotlin

A nested try-catch block is one in which one try-catch block is used to implement another try-catch block. A nested try-catch block is required when a piece of code throws an exception, and another code statement within that block throws another exception.

Syntax:

try    

{    

    // code block   

    try    

    {    

        // code block   

    }    

    catch(e: SomeException)    

    {    

    }    

 }    

catch(e: SomeException)    

{    

 }  

Let's take a look at a Nested try-catch example.

Kotlin_Try_Catch_5

In this example, there is an exception in the inner try block, but the occurred exception is ArithmeticException is not handled in the inner catch blocks, so the outer catch blocks are checked for this exception since the outer catch block is handling this exception, the code inside outer catch block is executed for ArithmeticException.

Master front-end and back-end technologies and advanced aspects in our Post Graduate Program in Full Stack Web Development. Unleash your career as an expert full stack developer. Get in touch with us NOW!

Conclusion

In this tutorial on Kotlin try-catch, you understood try block and catch block and learned why we use try and catch expressions in Kotlin. You also learned about multiple catch blocks in Kotlin and understood the Nested try-catch block in Kotlin with the help of examples.

If you are looking to build a software development career, you can check the Post-Graduate Program in Full Stack Development by Simplilearn. It can be the ideal solution to help you build your career in the right direction.

Do you have any questions about this Kotlin try-catch tutorial? If you do, then you can put them in the comments section. We’ll help you solve your queries at the earliest. 

Our Software Development Courses Duration And Fees

Software Development Course typically range from a few weeks to several months, with fees varying based on program and institution.

Program NameDurationFees
Caltech Coding Bootcamp

Cohort Starts: 17 Jun, 2024

6 Months$ 8,000
Full Stack Developer - MERN Stack

Cohort Starts: 24 Apr, 2024

6 Months$ 1,449
Automation Test Engineer

Cohort Starts: 1 May, 2024

11 Months$ 1,499
Full Stack Java Developer

Cohort Starts: 14 May, 2024

6 Months$ 1,449