SyntaxDoes "raise" trigger exception?RescueRescue all exceptionsRescue from StandardErrorRaiseRaise a single stringRelated Articles
Syntax
begin
# raise 'A test exception.'
puts "I'm not raising exception"
rescue Exception => e
puts e.message
puts e.backtrace.inspect
else
puts "Congratulations-- no errors!"
ensure
puts "Ensuring execution"
end
# I'm not raising exception
# Congratulations-- no errors!
# Ensuring execution
Does "raise" trigger exception?
Short answer: yes
Long answer: what exception are you raising? what exception are you capturing?
Rescue
Rescue all exceptions
rescue Exception
Rescue everything is a bad idea because it includes
SyntaxError
, LoadError
, and Interrupt
.- Rescuing
Interrupt
prevents the user from using CTRLC to exit the program.
- Rescuing
SignalException
prevents the program from responding correctly to signals. It will be unkillable except by kill -9.
Rescue from StandardError
rescue
without a parameter just rescues exceptions that inherit from StandardError
These three all rescue from
StandardError
.begin
# iceberg!
rescue
# lifeboats
end
begin
# iceberg!
rescue => e
# lifeboats
end
begin
# iceberg!
rescue StandardError => e
# lifeboats
end
Raise
raise exception-type "exception message" condition
Raise a single string
With a single String argument, raises a RuntimeError with the string as a message.
(RuntimeError inherit from StandardError)
raise "this is an error"
Related Articles
Â