The Programmers Guide To Kotlin - Exceptions
Written by Mike James   
Thursday, 30 July 2020
Article Index
The Programmers Guide To Kotlin - Exceptions
Finally

And Finally

You can also add a finally block at the end, and this contains code that will always be executed no matter what happens. The finally block is an important facility because it can be used to remove resources that might have been created. The classic example is to use a finally block to close all the files that might have been opened.

Notice that a finally block is called whether or not an exception has occurred. As a result it is sometimes useful to have a try block with a finally and no catch blocks.

For example:

try{
 do lots of things
}
finally{  clean up after doing lots of things }

A finally block will be executed, even if the try block contains a return that ends the function.

One big difference between Java and Kotlin is that the try block is actually an expression. Its value is the last expression in the try or the catch that is executed. It is also worth pointing out that the try block is a nested block and hence any variables you might declare within it are local to that block.

So for example:

try{
    var result=a/b
}

in this case result isn't available outside of the try block. However, as try is an expression:

var result=try{
    a/b }
catch(e:ArithmeticException){   0 }

you can access the result of the division in the main program and the result is zero if an exception occurs. If the try or catch block doesn't return a value then the expression evaluates to Unit.

Another big difference between Kotlin and Java exceptions is that Kotlin doesn't have checked exceptions. Put simply, a checked exception is one that you have to handle and the compiler does a compile-time check to make sure you have. This seemed like a good idea when it was first introduced into Java, but it resulted a great many catch clauses that didn't do anything - either because there was no time to create something meaningful or the programmer knew that an exception of the type was logically impossible.

You can argue about the usefulness of checked exceptions, but Kotlin doesn't have them.

You can create your own exceptions by creating a subclass of Throwable or one of the existing exception classes. To throw an exception all you have to do is create an instance of the exception class and use it in a throw statement:

throw myException()

You can throw an exception from within an exception handler, i.e. a try or catch block, and this is a common way of passing exceptions to other handlers.

Just as try is an expression, so is throw, but it returns the Nothing type. Of course, a throw doesn't allow execution to continue, so it might seem strange to have a value at all. The only point of throw returning Nothing is that it allows it to be included in expressions, i.e. the compiler doesn't complain if you write things like:

val myVal=myObject.name ?: throw myException()

This either assigns myVal a non null value, or it throws an exception and stops the evaluation.

The big problem with exception handling is the cost of implementing anything that works reasonably well from the user’s point of view. Every task within a program should be protected by an exception handler that attempts to recover the situation. This can increase the amount of code needed by a factor of at least ten. While it is difficult to write a program that works when everything goes according to plan, it is next to impossible to write one that still works when things start to go wrong.

Exceptions are a good idea, rarely used sufficiently.

 

kotlinlogo

 

Summary 

  • An exception is an error or a fault condition that is difficult to test for before it happens.

  • Exceptions allow you to unwind the call stack to get back to an earlier condition that represents things before the error occurred so that you can have another attempt.

  • In Kotlin exceptions are handled using a try catch block:
    try{instructions}catch(exception){handler}

  • You can also add a finally block at the end, and this contains code that will always be executed no matter what happen.

  • The try block is an expression that returns the value of the last expression in the try or catch.

  • There are no checked exceptions in Kotlin.

  • You can throw your own exceptions using the throw command.

This article is an extract from: 

Programmer's Guide To Kotlin Second Edition

kotlin2e360

You can buy it from: Amazon

Contents

  1. What makes Kotlin Special
  2. The Basics:Variables,Primitive Types and Functions 
  3. Control
         Extract: If and When 
  4. Strings and Arrays
  5. The Class & The Object
  6. Inheritance
  7. The Type Hierarchy
  8. Generics
  9. Collections, Iterators, Sequences & Ranges
        Extract: Iterators & Sequences 
  10. Advanced functions 
  11. Anonymous, Lamdas & Inline Functions
  12. Data classes, enums and destructuring
        Extract: Destructuring 
  13. Exceptions, Annotations & Reflection
  14. Coroutines
        Extract: Coroutines 
  15. Working with Java
        Extract: Using Swing ***NEW!

<ASIN:B096MZY7JM>

To be informed about new articles on I Programmer, sign up for our weekly newsletter, subscribe to the RSS feed and follow us on Twitter, Facebook or Linkedin.

Banner


Java Version 22 Released
04/04/2024

JDK 22 is not a Long Term Support release, but is one of the regular releases that are scheduled to arrive every six months. Still, it has got a lot to show for itself.



The University of Tübingen's Self-Driving Cars Course
22/03/2024

The recorded lectures and the written material of a course on Self-Driving Cars at the University of Tübingen have been made available for free. It's a first class opportunity to learn the in an [ ... ]


More News

raspberry pi books

 

Comments




or email your comment to: comments@i-programmer.info

<ASIN:1871962536>

<ASIN:1871962544>



Last Updated ( Monday, 03 August 2020 )