Introduction
Begin/rescue/end blocks help your program handle errors without crashing. They let you try code and catch problems if they happen.
Begin/rescue/end blocks help your program handle errors without crashing. They let you try code and catch problems if they happen.
begin # code that might cause an error rescue SomeErrorClass # code to handle the error end
begin and end.rescue part runs only if an error happens.begin puts 10 / 0 rescue ZeroDivisionError puts "Can't divide by zero!" end
begin file = File.open('missing.txt') rescue Errno::ENOENT puts "File not found." end
This program asks for a number, tries to divide 100 by it, and handles two errors: invalid input and division by zero.
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
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.
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.
begin/rescue/end block in Ruby?begin blockbegin block contains code that might cause an error.rescue blockrescue block catches errors and handles them so the program doesn't crash.begin/rescue/end in Ruby?begin, rescue, and end keywords for exceptions.begin puts 10 / 0 rescue ZeroDivisionError puts "Cannot divide by zero" end
begin puts 5 + "3" rescue puts "Error caught" end
begin # risky code rescue puts "An error occurred" end
rescue ZeroDivisionError and rescue IOError to handle errors distinctly.Pass the test and this pattern moves unknown