BeginnersBook

  • Home
  • Java
    • Java OOPs
    • Java Collections
    • Java Examples
  • C
    • C Examples
  • C++
    • C++ Examples
  • DBMS
  • Computer Network
  • Python
    • Python Examples
  • More…
    • jQuery
    • Kotlin
    • WordPress
    • SEO
    • JSON
    • JSP
    • JSTL
    • Servlet
    • MongoDB
    • XML
    • Perl

Kotlin Try as an expression in Exception handling

By Chaitanya Singh | Filed Under: Kotlin Tutorial

The try block in Kotlin can work as an expression. It can return a value just like any other expression, the returned value can be stored in a variable. In this guide, we will learn how to use try as an expression in Kotlin.

Kotlin try as an expression example

In the following example try block is working as an expression, the value returned by try can be stored in the variable as shown in the following example.

fun main(args: Array<String>) {
    var website = "Beginnersbook.com"
    var num = try {
        website.toInt()
    }
    catch (e: NumberFormatException)
    {
        "Cannot convert String to integer"
    }
    println(num)

    var number = "100"
    var num2 = try {
        number.toInt()
    }
    catch (e: NumberFormatException)
    {
        "Cannot convert String to integer"
    }
    println(num2)
}

Output:
Kotlin try expression

❮ PreviousNext ❯

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Kotlin Tutorial

  • Kotlin Tutorial
  • Kotlin in Eclipse IDE
  • Kotlin in IntelliJ
  • First Kotlin Program
  • Kotlin Keywords
  • Kotlin Variables
  • Kotlin Type Casting
  • Kotlin operators
  • Kotlin Input/Output
  • Kotlin Comments

Kotlin String

  • Kotlin String

Kotlin Array

  • Kotlin Array
  • Kotlin Range

Control Flow

  • Kotlin if expression
  • Kotlin when expression
  • Kotlin for loop
  • Kotlin while loop
  • Kotlin do-while loop
  • Kotlin continue
  • Kotlin break

Kotlin Function

  • Kotlin Function
  • Kotlin Recursion
  • Kotlin default and named arguments
  • Lambda functions
  • Higher Order Function

Exception Handling

  • Exception Handling
  • Kotlin try catch
  • Multiple catch blocks
  • Nested try catch
  • Throw keyword
  • Kotlin try expression

Kotlin OOP

  • Class and Objects
  • Kotlin Constructors
  • Kotlin Inheritance
  • Visibility Modifiers
  • Kotlin abstract class
  • Kotlin Interfaces
  • Nested and Inner Class
  • Kotlin Data Class
  • Kotlin Sealed Class

Copyright © 2012 – 2022 BeginnersBook . Privacy Policy . Sitemap