xxxxxxxxxx
# Ruby program to illustrate
# use of else statement
begin
# using raise to create an exception
# raise 'Exception Created!'
puts 'no Exception raise'
# using Rescue method
rescue
puts 'Finally Saved!'
# using else statement
else
puts 'Else block execute because of no exception raise'
# using ensure statement
ensure
puts 'ensure block execute'
end
xxxxxxxxxx
begin # "try" block
puts 'I am before the raise.'
raise 'An error has occurred.' # optionally: `raise Exception, "message"`
puts 'I am after the raise.' # won't be executed
rescue # optionally: `rescue Exception => ex`
puts 'I am rescued.'
ensure # will always get executed
puts 'Always gets executed.'
end
xxxxxxxxxx
# Ruby program to create the user
# defined exception and handling it
# defining a method
def raise_and_rescue
begin
puts 'This is Before Exception Arise!'
# using raise to create an exception
raise 'Exception Created!'
puts 'After Exception'
# using Rescue method
rescue
puts 'Finally Saved!'
end
puts 'Outside from Begin Block!'
end
# calling method
raise_and_rescue
xxxxxxxxxx
# Ruby program to illustrate
# use of retry statement
begin
# using raise to create an exception
raise 'Exception Created!'
puts 'After Exception'
# using Rescue method
rescue
puts 'Finally Saved!'
# using retry statement
retry
end
xxxxxxxxxx
# Ruby program to illustrate
# use of ensure statement
begin
# using raise to create an exception
raise 'Exception Created!'
puts 'After Exception'
# using Rescue statement
rescue
puts 'Finally Saved!'
# using ensure statement
ensure
puts 'ensure block execute'
end
xxxxxxxxxx
# Ruby program to illustrate
# use of raise statement
begin
puts 'This is Before Exception Arise!'
# using raise to create an exception
raise 'Exception Created!'
puts 'After Exception'
end
xxxxxxxxxx
# Ruby program to illustrate
# use of catch and throw statement
# defining a method
def catch_and_throw(value)
puts value
a = readline.chomp
# using throw statement
throw :value_e if a == "!"
return a
end
# using catch statement
catch :value_e do
# enter number
number = catch_and_throw("Enter Number: ")
end