DEV Community

Ted Hagos
Ted Hagos

Posted on • Originally published at workingdev.net on

1

Kotlin Exception handling

Kotlin's approach to exception is similar to Java. Somewhat. It uses the try-catch-finally, just like in Java. So, your knowledge about how try-catch works commutes nicely to Kotlin. The code below should be very familiar. It shows a typical code on how to open a file

import java.io.FileNotFoundException
import java.io.FileReader
import java.io.IOException

fun main(args: Array<String>) {
  var fileReader: FileReader
    try {
    fileReader = FileReader("README.txt")
    var content = fileReader.read()
    println(content)
 }
  catch (ffe: FileNotFoundException) {
    println(ffe.message)
  }
  catch(ioe: IOException) {
    println(ioe.message)
 }
}
Enter fullscreen mode Exit fullscreen mode

So, what's different? Well, in Kotlin, everything is an unchecked exception. Which means, the try-catch block is optional. It's up to the programmer if you want to use it. So, the code above, can be written like this (in Kotlin).

import java.io.FileReader  

fun main(args: Array<String>) {
  var fileReader = FileReader("README.txt")  
  var content = fileReader.read()  
  println(content)
}
Enter fullscreen mode Exit fullscreen mode

So how do you know if you need to use try-catch. You might not like the answers now, but in the long run, these are good advice to follow ;

  1. You have to know the API's you're using. I know that this is not great news for beginners, but look at it this way, you won't be a beginner for long. And you really should know the API's you're using. TL;DR won't serve you well in this area
  2. You have to get into the habit of unit-testing your code. This is a good habit to develop anyway

AWS GenAI LIVE image

How is generative AI increasing efficiency?

Join AWS GenAI LIVE! to find out how gen AI is reshaping productivity, streamlining processes, and driving innovation.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay