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

Now Available as a Print Book

cover

You can buy it from: Amazon

Contents

Some Chapters Already Available On The Web

  1. What makes Kotlin Special (Book Only)
  2. The Basics: Variables, Primitive Types and Functions
  3. Control
  4. Strings and Arrays
  5. The Class & The Object
  6. Inheritance
  7. The Type Hierarchy 
            Extract  Type and its problems
            Extract  Smart Casts
  8. Generics
            Extract Basic Generics
            Extract Covariance & Contravariance
  9. Collections, Iterators, Sequences & Ranges
            Extract     Collections
            Extract Iterators & Sequences
  10. Advanced functions 
  11. Anonymous, Lamdas & Inline Functions
            Extract    Annoymous and Lambda Functions
            ExtractInline Functions
  12. Data classes, enums and destructuring
            Extract  Data Classes
            Extract      Enums & Sealed Classes 
            Extract 
         Delegated Properties 
            Extract      Destructuring  **NEW!**
  13. Exceptions, Annotations & Reflection
            Extract Exceptions
            Extract Annotation & Reflection 
  14. Working with Java
            Extract Using Swing  

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


Lightstep Adds New GitHub Action
22/10/2020

Lightstep has announced a new GitHub action, Lightstep Pre-Deploy Check, designed to help developers be proactive about ensuring the quality and performance of their software before it’s actually de [ ... ]



DevFest 2020 - Largest Virtual Google Developer Event
09/10/2020

Like so much this year,  DevFest is happening virtually. Taking place October 16-18, it still intends to bring together thousands of developers globally for a weekend of community-led technical l [ ... ]


More News

square

 



 

Comments




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

<ASIN:1871962536>

<ASIN:1871962544>



Last Updated ( Monday, 03 August 2020 )