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.
The handling of an exception is identical to Java, with the use of try, catch, and finally blocks.
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() } }