ProgramGuru

Exceptions and deliberate failure handling

Exceptions and deliberate failure handling

A score form can receive a number outside the accepted range. Recoverable failure should be expressed in the function’s contract so callers decide how to respond. A throwing function can produce a value or throw an error; do-catch handles that error at the call site.

What you’ll learn

  • Distinguish successful return and exception handling.
  • Use finally without overstating its guarantees.

Exceptions and deliberate failure handling in the example

  1. Validate range

    A score form can receive a number outside the accepted range.

    Validate range
  2. Throw on failure

    Kotlin can throw exceptions and use try-catch to handle them.

    Throw on failure
  3. Catch and explain

    The requirement throws before a score is returned.

    Catch and explain
The requirement throws before a score is returned. The catch displays Invalid score, and finally runs when this try operation exits. A normal return of 80 would instead print the score and still run the final message.

Understand exceptions and deliberate failure handling

Kotlin can throw exceptions and use try-catch to handle them. Try can also produce a value. Kotlin does not require Java-style checked-exception declarations, but callers still need to understand a function’s possible failures. Catch a relevant type rather than blindly swallowing every failure.

Follow exceptions and deliberate failure handling

Save the complete source as Main.kt and use the Kotlin/JVM environment. No separate input file is needed.

Kotlin/JVM · complete program

fun validScore(score: Int): Int {
  require(score in 0..100) { "Score must be 0..100" }
  return score
}
fun main() {
  try { println(validScore(120)) }
  catch (e: IllegalArgumentException) { println("Invalid score") }
  finally { println("Check finished") }
}

Expected output

Invalid score
Check finished

Follow the execution

The requirement throws before a score is returned. The catch displays Invalid score, and finally runs when this try operation exits. A normal return of 80 would instead print the score and still run the final message.

Try this in the Kotlin compiler by pasting the complete program.

Practice: Exceptions and deliberate failure handling

Your task: What happens when validScore receives 80?

Kotlin/JVM · complete program

fun validScore(score: Int): Int {
  require(score in 0..100) { "Score must be 0..100" }
  return score
}
fun main() {
  try { println(validScore(120)) }
  catch (e: IllegalArgumentException) { println("Invalid score") }
  finally { println("Check finished") }
}

Worked answer

It returns 80 without entering this catch; Check finished still prints from finally.

Exceptions and deliberate failure handling: the important boundary

Use require for invalid arguments and check for inappropriate state when those contracts fit. For ordinary recoverable absence, nullable or explicit result types can be clearer. Coroutine cancellation needs propagation rather than being hidden by broad catch blocks.

Check your understanding

What happens when validScore receives 80?
Choose one answer. You can try again.

Answer and explanation

It returns 80 without entering this catch; Check finished still prints from finally..

It returns 80 without entering this catch; Check finished still prints from finally.

Exceptions and deliberate failure handling: what to keep in mind

It returns 80 without entering this catch; Check finished still prints from finally. Use require for invalid arguments and check for inappropriate state when those contracts fit.

Further reading: official Kotlin documentation for this topic.

Reaching the recap and completing the quizzes are separate milestones.

    Next lesson: Files and resource cleanup on the JVM →