With exception handling features of a language, you can deal with unpredicted situations or exceptional states that can occur while your code is executing. Kotlin is no different from other languages, like C# and Java and has the same keywords for handling exceptions. These are try
, catch
, and finally
. With these keywords, you can execute a function or some other action which may fail, execute some code in case of failure, and do a cleanup of resources.
val file = File("foo") var stream: OutputStream? = null try { stream = file.outputStream() //do something with stream } catch (ex: FileNotFoundException) { println("File doesn't exist") } finally { if (stream != null) stream.close() }
When you detect an error, or an exceptional state has occurred, you can tell that to the runtime by raising an exception. The caller of your function can catch that exception and try to recover it from an exceptional state. If he doesn’t, then the exception is thrown further up the function call...