I’m not exactly sure what you mean. If you only want to change how
errors are displayed, why not simply wrap the whole script in a
begin-end block?
Single begin-end blocks are only necessary if you actually want to do
something specific with the error (like retrying or ignoring). It
doesn’t make sense to write the same error handler for every code that
may fail.
However, there are ways to shorten error code. For single statements,
you can use the rescue modifier:
“” + 1 rescue puts ‘Rescued!’
This catches any StandardError raised by the statement before the
“rescue”.
You may also write a method that takes a block and catches errors from
it:
def try_and_catch
begin
yield
rescue
puts ‘Rescued!’
end
end
I could also use other methods perhaps, rather than begin, use something
like:
rescue_verbose {
code_that_may_fail_here
}
def rescue_verbose
yield
rescue => e
puts e
end
rescue_verbose { 1 / 0 }
Note: you would be advised not to rescue Exception, but instead rescue
StandardError (which is the default if you don’t specify a class).
Exception includes things you almost certainly don’t want to rescue,
like SyntaxError, NoMemoryError, and Interrupt.
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.