Error Contracts
Lesson 28 of 48 in Coddy's Rust for Kotlin Developers course.
Kotlin exception subclasses can distinguish failure causes, while sealed result types are another explicit design option. Rust commonly uses a domain enum inside Result so callers can match stable error variants rather than parse human-readable messages. The example classifies a filename extension.
Failure contracts also describe state: some operations preserve the original state on rejection, while others report partial progress. Neither exceptions nor Result automatically roll back earlier mutations. This example is stateless, so the later stateful task must deliberately separate validation from committing changes. Test both the reported reason and what remains unchanged when atomic rejection is required. A narrow error type helps callers choose recovery, but it does not itself implement transaction semantics.
Kotlin: complete program
class BadExtension : Exception()
fun checkName(name: String) {
if (!name.endsWith(".txt")) throw BadExtension()
}
fun main() {
try { checkName("note.tmp"); println("ok") }
catch (error: BadExtension) { println("extension") }
}
Rust: complete program
enum FileError { Extension }
fn check(name: &str) -> Result<(), FileError> {
if name.ends_with(".txt") { Ok(()) } else { Err(FileError::Extension) }
}
fn main() {
match check("note.tmp") { Ok(()) => println!("ok"), Err(FileError::Extension) => println!("extension") }
}Returning Err after changing a field does not undo that assignment.
Challenge
EasyImplement public DebitError variants NonPositive and Insufficient, deriving Debug and PartialEq, and pub fn debit(balance: &mut i32, amount: i32) -> Result<i32, DebitError> in account.rs. Starting balances are nonnegative and arithmetic fits i32. Reject an amount of zero or less with NonPositive; otherwise reject an amount greater than the balance with Insufficient. Every failure leaves balance unchanged. On success subtract amount and return the new balance. Input is starting balance followed by debit amounts. solve applies them in order and returns final|statuses, with statuses ok:new, nonpositive or insufficient, comma-separated. With no amounts the suffix is empty.
Implement the required exported APIs and return the result from exercise::solve(input: &str) -> String without a final newline. Do not print in editable code. The locked driver checks required APIs independently, reads all stdin, and prints the returned text with one final newline.
Your code goes in exercise.rs, account.rs. main.rs holds the supplied input/output code and cannot be edited.
Try it yourself
#![allow(dead_code, unused_imports, unused_variables, unused_mut)]
mod exercise;
mod account;
use std::io::{self, Read};
fn main() {
let mut input=String::new();
io::stdin().read_to_string(&mut input).unwrap();
// BEGIN PUBLIC API PROBES
let mut balance = 37;
assert_eq!(account::debit(&mut balance, 12), Ok(25));
assert_eq!(account::debit(&mut balance, 26), Err(account::DebitError::Insufficient));
assert_eq!(balance, 25);
assert_eq!(account::debit(&mut balance, -4), Err(account::DebitError::NonPositive));
assert_eq!(balance, 25);
assert_eq!(account::debit(&mut balance, 0), Err(account::DebitError::NonPositive));
assert_eq!(balance, 25);
assert_eq!(account::debit(&mut balance, 25), Ok(0));
assert_eq!(account::debit(&mut balance, 1), Err(account::DebitError::Insufficient));
assert_eq!(balance, 0);
// END PUBLIC API PROBES
println!("{}", exercise::solve(&input));
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Rust for Kotlin Developers
1First Rust Programs
Run Rust ModulesOutput and CommentsModules and VisibilityBindings and TypesNumbers and CastsRecap: Storage Invoice4Ownership and Borrowing
Ownership and MovesShared BorrowsMutable BorrowsLifetimes and ViewsBorrowing Recap3Functions and Sequences
Functions and ReturnsArrays and SlicesVectors and IterationRecap: Record Readings6Absence and Failure
Option and MatchingResult and PropagationParsing and ValidationError ContractsFailure RecapPractice on your own: Online Rust compiler