0
0
Rubyprogramming~5 mins

Begin/rescue/end blocks in Ruby

Choose your learning style9 modes available
Introduction

Begin/rescue/end blocks help your program handle errors without crashing. They let you try code and catch problems if they happen.

When reading a file that might not exist.
When dividing numbers and the divisor could be zero.
When connecting to the internet and the connection might fail.
When converting user input to a number that might be invalid.
Syntax
Ruby
begin
  # code that might cause an error
rescue SomeErrorClass
  # code to handle the error
end
You put the risky code inside begin and end.
The rescue part runs only if an error happens.
Examples
This catches a division by zero error and prints a friendly message.
Ruby
begin
  puts 10 / 0
rescue ZeroDivisionError
  puts "Can't divide by zero!"
end
This tries to open a file and handles the case when the file is missing.
Ruby
begin
  file = File.open('missing.txt')
rescue Errno::ENOENT
  puts "File not found."
end
Sample Program

This program asks for a number, tries to divide 100 by it, and handles two errors: invalid input and division by zero.

Ruby
begin
  puts "Enter a number:"
  num = Integer(gets.chomp)
  puts "100 divided by your number is #{100 / num}"
rescue ArgumentError
  puts "That's not a valid number!"
rescue ZeroDivisionError
  puts "Can't divide by zero!"
end
OutputSuccess
Important Notes

You can have multiple rescue clauses to handle different errors.

If no error happens, the rescue part is skipped.

Use ensure after rescue if you want code to run no matter what.

Summary

Use begin/rescue/end to catch and handle errors safely.

Put risky code inside begin and handle errors in rescue.

This helps your program keep running even when something goes wrong.