Exceptions

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 stack.

Exceptions are raised with the  throw keyword. You can create your own Exception types by extending the base Exception class from the Java standard library or by implementing the throwable interface. You’ll learn more about extending classes and implementing interfaces in the next chapter. Most of the time, creating your own Exception type will not be needed. The Java and Kotlin Standard Libraries have numerous Exception types that cover most common programming errors. This is how you would throw an exception if a number is not in the range from 1 to 10:

if (num !in 1..10) throw IllegalArgumentException("Number has to be from 1 to 10")

Both try and throws keywords in Kotlin are expressions, that is, they can return a value. The following example shows how throws can be used as an expression:

val divide = if (divisor > 0) {
value / divisor
} else {
throw IllegalArgumentException("Can’t divide with 0")
}

Finally, Kotlin doesn’t have checked exceptions. Checked exceptions are a type of exception that have to be either declared or caught in the function in which they are thrown. In other words, they have to be handled explicitly.

Not many other languages have checked exceptions, but Java is one of them. If you don’t want to ignore the exception, then Java requires a lot of code just to rethrow the exception in a catch block.

Since Kotlin doesn’t have checked exceptions, you don’t have to catch them. For example, if you are calling a Java function that throws a checked exception, the Kotlin compiler will not force you to wrap the function call inside a try/catch block, like the Java compiler would.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
52.14.127.57