0
0
Rubyprogramming~5 mins

Why error handling uses rescue in Ruby

Choose your learning style9 modes available
Introduction

Error handling uses rescue to catch problems in your code so the program can keep running without crashing.

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 run if error happens
end

begin starts the block where errors might happen.

rescue catches the error and lets you handle it safely.

Examples
This catches the error when dividing by zero and prints a message instead of crashing.
Ruby
begin
  1 / 0
rescue ZeroDivisionError
  puts "Can't divide by zero!"
end
This handles the error if the file does not exist.
Ruby
begin
  file = File.read('missing.txt')
rescue Errno::ENOENT
  puts "File not found!"
end
This catches the error when trying to convert a bad string to a number.
Ruby
begin
  number = Integer('abc')
rescue ArgumentError
  puts "Invalid number!"
end
Sample Program

This program asks the user for a number and divides 10 by it. It uses rescue to handle if the user enters zero or something that is not a number.

Ruby
begin
  puts "Enter a number to divide 10 by:"
  input = gets.chomp
  divisor = Integer(input)
  result = 10 / divisor
  puts "Result is #{result}"
rescue ZeroDivisionError
  puts "You can't divide by zero!"
rescue ArgumentError
  puts "That's not a valid number!"
end
OutputSuccess
Important Notes

You can have multiple rescue clauses to handle different errors.

If you don't handle errors, your program might stop unexpectedly.

Summary

rescue helps your program handle errors without crashing.

Use rescue to catch specific errors and respond nicely.

This makes your programs more user-friendly and reliable.