Exceptions and Validation
Lesson 23 of 48 in Coddy's Ruby for Rust Developers course.
Rust commonly returns Result for recoverable failure, while panic is a separate mechanism. Ruby uses raise/rescue and bare rescue catches StandardError subclasses. Converting a Result into an exception is an API choice. Neither a failed Result nor a Ruby exception automatically restores earlier mutations, so validation order matters.
Rust: complete program
fn main() {
let result:Result<i32,&str>=Err("bad"); match result {Ok(n)=>println!("{}",n),Err(_)=>println!("caught")};
}
Ruby: complete program
begin
puts({}.fetch("oak"))
rescue KeyError
puts "missing"
end
puts "after"Challenge
EasyDefine parse_count(text): accept exactly one or more ASCII decimal digits, then convert to an integer. Raise ArgumentError otherwise. solve strips its whole input, returns the number, or invalid when ArgumentError is raised.
Return text from solve(input) without printing. The locked driver prints the returned text with one final newline and checks required public APIs independently.
Your code goes in exercise.rb, parser.rb. main.rb holds the supplied input/output code and cannot be edited.
Try it yourself
require_relative 'exercise'
require_relative 'parser'
def check(value)
raise 'Public API check failed' unless value
end
check(parse_count("009") == 9)
["-1", "", "2x", "4\n"].each do |s|
begin
parse_count(s)
raise "Expected ArgumentError"
rescue ArgumentError
end
end
puts solve(STDIN.read)
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Ruby for Rust Developers
1Start with Ruby
Run Ruby FilesOutput and CommentsNames and ObjectsInteger ArithmeticTruth and Boolean LogicString OperationsSymbols and KeysRecap: Packing Slip4Mutation and Errors
Mutation and AliasesNil and Optional ValuesExceptions and ValidationEnsure and CleanupRecap: Safe Ratio2Flow and Methods
Conditional ValuesCase and RangesLoops and Early ExitMethods and ReturnsDefaults and KeywordsRecap: Sensor Run5Objects and State
Modules as NamespacesClasses and InstancesReaders and WritersValidated ConstructionRecap: Wallet8Lending Desk Project
Lending Desk: CatalogLending Desk: BorrowPractice on your own: Online Ruby compiler