How to Use begin rescue in Ruby for Error Handling
In Ruby, use
begin and rescue to handle errors by wrapping code that might fail inside begin and catching exceptions with rescue. This lets your program continue running even if an error occurs.Syntax
The begin block contains code that might raise an error. The rescue block catches and handles the error. You can also use else for code that runs if no error happens, and ensure for code that always runs.
- begin: Start of the block that may raise an error.
- rescue: Handles exceptions raised in the
beginblock. - else: Runs if no exceptions occur.
- ensure: Runs always, whether an error occurred or not.
ruby
begin # code that might raise an error rescue SomeErrorClass => e # code to handle the error else # code that runs if no error ensure # code that always runs end
Example
This example shows how begin and rescue catch a division by zero error and handle it gracefully.
ruby
begin puts "Enter a number to divide 10 by:" number = gets.chomp.to_i result = 10 / number puts "Result is #{result}" rescue ZeroDivisionError => e puts "Error: Cannot divide by zero!" end
Output
Enter a number to divide 10 by:
0
Error: Cannot divide by zero!
Common Pitfalls
One common mistake is rescuing Exception which catches too many errors, including system errors you usually don't want to handle. Another is rescuing without specifying the error type, which can hide bugs. Also, forgetting to use rescue inside begin causes unhandled exceptions.
ruby
begin # risky code rescue puts "An error happened" end # Better to specify error type: begin # risky code rescue ZeroDivisionError => e puts "Handled division error: #{e.message}" end
Quick Reference
| Keyword | Purpose |
|---|---|
| begin | Start block of code that might raise errors |
| rescue | Catch and handle specific errors |
| else | Run code if no errors occur |
| ensure | Run code always, even if error occurs |
Key Takeaways
Use
begin and rescue to catch and handle errors in Ruby.Always specify the error type in
rescue to avoid hiding bugs.Use
else for code that runs only if no error occurs.Use
ensure for code that must run regardless of errors.Avoid rescuing
Exception to prevent catching system errors unintentionally.