Raising Exceptions

Frequently, we do not need to raise our own exceptions. We just deal with the ones that arise from the code that we write, where those exceptions get raised by Kotlin, libraries, etc.

However, from time to time, you might want to throw an exception yourself.

Here, once again, Kotlin works like Java. To throw an exception:

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

  return nullAllowedButNotReally!!.length
}

fun main() {
  println(lengthifier(null))
}

Here, we manually check to see if we received null in lengthifier(), and we throw our own Exception if that is the case. So, if we run this, we get our Exception:

Exception: Please do not pass null to me!

Prev Table of Contents Next

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