begin / rescue
Part of the Logic & Flow section of Coddy's Ruby journey — lesson 44 of 56.
To stop an exception from crashing your program, wrap the risky code in begin ... rescue ... end. If anything inside begin raises, Ruby jumps to the matching rescue block instead of aborting.
begin
result = 10 / 0
puts result
rescue ZeroDivisionError
puts "Cannot divide by zero!"
end
# Cannot divide by zero!You can grab the exception object itself with => e and read its .message:
begin
Integer("hello")
rescue ArgumentError => e
puts "Bad input: #{e.message}"
end
# Bad input: invalid value for Integer(): "hello"If you don't name an exception class, rescue on its own catches StandardError and its descendants, most everyday failures. Catching is most useful when you can do something in the rescue block: substitute a default value, log the problem, ask the user again.
Challenge
EasyRead two lines from input, both should be integers, but the second one might not be a valid number.
Wrap the parsing of the second line in begin / rescue:
- Use
Integer(input)(which raisesArgumentErroron a bad string) - If parsing succeeds, print
Sum: <a + b> - If it fails, print
Bad number!
For input 3 then 4, the output is Sum: 7. For 3 then abc, it's Bad number!.
Cheat sheet
Use begin ... rescue ... end to handle exceptions without crashing:
begin
result = 10 / 0
rescue ZeroDivisionError
puts "Cannot divide by zero!"
endCapture the exception object with => e to access its message:
begin
Integer("hello")
rescue ArgumentError => e
puts "Bad input: #{e.message}"
endUsing rescue without a class catches StandardError and its descendants.
Try it yourself
a = gets.to_i
raw_b = gets.chomp
# TODO: begin/rescue around Integer(raw_b); print sum or "Bad number!"
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Strings In Depth
String Methods OverviewString InterpolationIterating Over StringsSplit and JoinRecap - String Weaver4Blocks, Procs & Lambdas
What is a Block?do..end vs BracesThe yield KeywordBlock ParametersProcs and LambdasRecap - Custom Iterator7Hashes Part 2
Hash.new with DefaultsIterating HashesNested HashesMerging and TransformingRecap - Frequency Counter10Project - Student Records
Project OverviewAdd Student5Enumerable Powerhouse
Select and RejectChaining MapReduce / Injectcount, all?, any?, none?group_by and partitionsort_by, min_by, max_byRecap - Data Pipeline8Advanced Decision Making
Case with Classes & RegexMulti-value whenTernary OperatorInline if / unlessRecap - Grade Classifier