admin管理员组文章数量:1292140
I'm writing a script that might exit normally in many different points in the program. The script currently always outputs a message to STDOUT in an ensure block, sorta like this:
begin
exit
ensure
puts "my message"
end
The problem is that if the script crashes, the message is output anyway, followed by the error messages. What I want to do is only output the message on an exit 0, something like this:
begin
exit 1
ensure
if is_this_a_normal_exit?()
puts 'my messsage'
end
end
Is there a way to do that?
I'm writing a script that might exit normally in many different points in the program. The script currently always outputs a message to STDOUT in an ensure block, sorta like this:
begin
exit
ensure
puts "my message"
end
The problem is that if the script crashes, the message is output anyway, followed by the error messages. What I want to do is only output the message on an exit 0, something like this:
begin
exit 1
ensure
if is_this_a_normal_exit?()
puts 'my messsage'
end
end
Is there a way to do that?
Share Improve this question asked Feb 13 at 11:01 tscheingeldtscheingeld 88710 silver badges24 bronze badges 1- 1 save the wanted status in a var and use it in the ensure block? – Fravadona Commented Feb 13 at 11:31
1 Answer
Reset to default 2When calling exit
, this is generally Kernel#exit
. This method basically throws a SystemExit
exception which may eventually result in the program being exited.
You can either rescue this exception or check it in the ensure block:
begin
exit
rescue SystemExit => e
puts "my message" if e.success?
# re-raise the error to actually cause the program to exit
raise
ensure
# Here you can still add code which is executed after handling
# (or not handling) any exceptions. If there was an exception,
# you can access it here with the $! global variable.
end
Note that there are other possible causes of a program being exited, some of which you can't catch at all (e.g. when calling Kernel#exit!
or when you or some other process sends a signal like SIGKILL
to kill your program). Also, when using threads, the SystemExit
exception may not be propagated to the main thread.
本文标签: rubyGetting exit status in ensure blockStack Overflow
版权声明:本文标题:ruby - Getting exit status in ensure block - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741546812a2384640.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论