Javatpoint Logo
Javatpoint Logo

Kotlin try catch

Kotlin try-catch block is used for exception handling in the code. The try block encloses the code which may throw an exception and the catch block is used to handle the exception. This block must be written within the method. Kotlin try block must be followed by either catch block or finally block or both.

Syntax of try with catch block

Syntax of try with finally block

Syntax of try catch with finally block

Problem without Exception Handling

Lets's see an example which causes exception which is not handled.

This above program generates an exception, which causes rest of code below the exception not executable.

Output:

Exception in thread "main" java.lang.ArithmeticException: / by zero
	at ExceptionHandlingKt.main(ExceptionHandling.kt:2)

Solution by exception handling

Let's see the solution of above problem by using try-catch block.

Output:

java.lang.ArithmeticException: / by zero
code below exception...

In the above program after implementing try - catch block, rest of code below exception executes.

Kotlin try block as an Expression

We can use try block as an expression which returns a value. The value returned by try expression is either the last expression of try block or the last expression of catch. Contents of the finally block do not affect the result of the expression.

Kotlin try as an expression example

Let's see an example of try-catch block as an expression which returns a value. In this example String value to Int which does not generate any exception and returns last statement of try block.

Output:

10

Let's modify the above code which generate an exception and return the last statement of catch block.

Output:

0





Please Share

facebook twitter google plus pinterest

Learn Latest Tutorials


Preparation


B.Tech / MCA