Use a modified begin/rescue

I have in my code several lines that look like so:

begin
code_that_may_fail_here
rescue Exception => error
pp error
end

Rather than this, I would like to use that here:

begin
code_that_may_fail_here
rescue_verbose
end

Or perhaps even:

begin {
code_that_may_fail_here
}

I could also use other methods perhaps, rather than begin, use something
like:

rescue_verbose {
code_that_may_fail_here
}

My most important question however is:

Can I somehow make this here:

rescue Exception => error
pp error

shorter in lines of code?

I want to use a method instead perhaps, and output the error message to
the user. Ideally in one line, without using “;”

Hi,

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

try_and_catch do
“” + 1
end

Marc H. wrote in post #1051488:

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.

| Privacy Policy | Terms of Service | Remote Ruby Jobs