Kotlin - Statement Exception handling

Introduction

Kotlin exception handling is almost identical to the way Java handles exceptions.

In Kotlin all exceptions are unchecked.

Checked exceptions must be declared as part of the method signature or handled inside the method.

Unchecked exceptions are those that do not need to be added to method signatures.

In Kotlin, since all exceptions are unchecked, they never form part of function signatures.

Handler

The handling of an exception is identical to Java, with the use of try, catch, and finally blocks.

  • Code that you wish to handle safely can be wrapped in a try block.
  • Zero or more catch blocks can be added to handle different exceptions
  • a finally block is always executed regardless of whether an exception was generated or not.
  • The finally block is optional, but at least one catch or finally block must be present.

Example

In this example, the read() function can throw an IOException.

The input stream must always be closed, regardless of whether the reading is successful or not, and so we wrap the close() function in a finally block:

fun readFile(path: Path): Unit { 
  val input = Files.newInputStream(path) 
  try { 
    var byte = input.read() 
    while (byte != -1) { 
      println(byte) 
      byte = input.read() 
    } 
  } catch (e: IOException) { 
    println("Error reading from file. Error was ${e.message}") 
  } finally { 
    input.close() 
  } 
}