Defining Exceptions

You might have a need to create your own custom exceptions.

For example, suppose you are calling a Web service. You will get errors back from that Web service in a variety of ways, such as:

You might decide to convert those error conditions into exceptions.

As with Java, you can create subclasses of Exception to represent your custom exceptions:

class GoAway(message: String) : Exception(message)

fun lengthifier(nullAllowedButNotReally: String?): Int {
  if (nullAllowedButNotReally == null) throw GoAway("Please do not pass null to me!")

  return nullAllowedButNotReally!!.length
}

fun main() {
  val result = try {
    lengthifier(null)
  }
  catch (away: GoAway) {
    -2
  }
  catch (e: Exception) {
    -1
  }

  println(result)
}

Here, we create a custom GoAway exception and throw it rather than an Exception.

If you have a set of related exception types, a class hierarchy (using open, abstract, or sealed) may be useful:

open class MathBoom(message: String) : Exception(message)

class DivideByZeroBoom : MathBoom("Please do not divide by zero")

fun divider(numerator: Double, denominator: Double): Double {
  if (denominator == 0.0) throw DivideByZeroBoom()

  return numerator / denominator
}

val result = try {
  divider(1.0, 0.0).toString()
}
catch (e: MathBoom) {
  "whatever"
}

println(result)

Prev Table of Contents Next

This book is licensed under the Creative Commons Attribution-ShareAlike 4.0 International license.