begin end

 Begin/end blocks are often used in conjunction with the rescue, else, and ensure statements to allow them to handle erroneous events in your code. This brings us into the realms of exception handling in Ruby

1.

Ruby rescue - 

begin # error encountered here rescue # error captured and handled here end

2.

# ruby_error.rb puts "Hello world!" begin file = File.open("/path/to/invalid_file.txt", "r") # raises error data = file.read file.close rescue puts "An error encountered while opening the file. Moving on.." end puts "Jell-O world!"

3.

begin # error encountered here rescue # error captured and handled here else # code to run if no error raised end

# ruby_error.rb puts "Hello world!" begin file = File.open("/path/to/file.txt", "r") # actual file data = file.read file.close rescue Errno::ENOENT => e # missing file error puts "Missing file error encountered while opening the file. Moving on." else # if there’s nothing to rescue puts "No error encountered. You are good to go!" end puts "Jell-O world!"

Output:

$ ruby ruby_error.rb
Hello world!
No error encountered. You are good to go!
Jell-O world!
.................................................
begin # error encountered here rescue # captured and handled here else # code to run if no error raised ensure # code to always run at the end end
.................................................

















Comments

Popular posts from this blog

Rails 7 Features :: Comparison with Rails 6 and Rails 5