Search code examples
rubyfunctionrescue

Ruby begin rescue end with if-then-else


I am kind of stuck with using begin-rescue-end with if-else-end. Please see the code snippet below.

def fn1
    unless fn2?
        puts "Message 1"
        return
    end

    puts "Message 2"
end

def fn2?
    begin
        <do action>
    rescue
        <handle error here>
        puts "Message 3"
        return
    end

    if <condition>
        puts "Message 4"
        return true
    else
        puts "Message 5"
        return false
    end
end

In the begin block, if there is no exception raised, then if-else will get executed and return true or false to fn1. No problem with this.

But in the begin block, should an exception be raised, I want to just print "Message 3" and end the program, without printing "Message 1".

Any pointers please. Thanks.


Solution

  • If you want to terminate the program (instead of just returning from fn2?), you can use Kernel#exit, for example:

    begin
        <do action>
    rescue
        <handle error here>
        puts "Message 3"
        exit(1)
    end