简体   繁体   English

Ruby从if-then-else开始抢救

[英]Ruby begin rescue end with if-then-else

I am kind of stuck with using begin-rescue-end with if-else-end. 我有点想将begin-rescue-end与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. 在begin块中,如果没有引发异常,则执行if-else并向fn1返回true或false。 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". 但是在开始块中,如果引发异常,我只想打印“消息3”并结束程序,而不打印“消息1”。

Any pointers please. 任何指针,请。 Thanks. 谢谢。

If you want to terminate the program (instead of just returning from fn2? ), you can use Kernel#exit , for example: 如果要终止程序(而不是仅从fn2?返回),可以使用Kernel#exit ,例如:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM