Syntax

Kotlin Try / Catch Syntax

In Kotlin, try / catch: handles exceptions (as an expression) — val n = try { s.toInt() } catch (e: NumberFormatException) { 0 }

Quick Answer

Syntax
val n = try { s.toInt() } catch (e: NumberFormatException) { 0 }
KotlinSyntax

Try / Catch

Code example
val n = try { s.toInt() } catch (e: NumberFormatException) { 0 }

Handles exceptions (as an expression).

Learn More

How to try / catch in Kotlin

  1. Open your Kotlin file or editor.
  2. Copy the example, then replace its sample names and values for your code.

Kotlin Try / Catch Syntax

Use val n = try { s.toInt() } catch (e: NumberFormatException) { 0 }.

Related Syntax References

Frequently asked questions

What is the Kotlin syntax for try / catch?

Use this pattern: val n = try { s.toInt() } catch (e: NumberFormatException) { 0 }

Can I copy this Kotlin code example?

Yes. Use Copy code and adapt the example to your program.

Is this Kotlin syntax different on Mac or Windows?

No. The language syntax is the same across operating systems.

Official source · How we verify