【发布时间】:2013-09-13 08:43:30
【问题描述】:
我正在尝试将一些 Python 代码转换为 Ruby。 Ruby 中是否有与 Python 中的 try 语句等效的语句?
【问题讨论】:
-
请显示一个代码!
-
查找 Ruby
rescue(和raise)
标签: python python-3.x ruby try-catch language-comparisons
我正在尝试将一些 Python 代码转换为 Ruby。 Ruby 中是否有与 Python 中的 try 语句等效的语句?
【问题讨论】:
rescue(和 raise)
标签: python python-3.x ruby try-catch language-comparisons
begin
some_code
rescue
handle_error
ensure
this_code_is_always_executed
end
详情:http://crodrigues.com/try-catch-finally-equivalent-in-ruby/
【讨论】:
以此为例:
begin # "try" block
puts 'I am before the raise.'
raise 'An error has occurred.' # optionally: `raise Exception, "message"`
puts 'I am after the raise.' # won't be executed
rescue # optionally: `rescue Exception => ex`
puts 'I am rescued.'
ensure # will always get executed
puts 'Always gets executed.'
end
Python 中的等效代码是:
try: # try block
print('I am before the raise.')
raise Exception('An error has occurred.') # throw an exception
print('I am after the raise.') # won't be executed
except: # optionally: `except Exception as ex:`
print('I am rescued.')
finally: # will always get executed
print('Always gets executed.')
【讨论】:
else 子句,只有在没有触发异常时才会执行。
如果要捕获特定类型的异常,请使用:
begin
# Code
rescue ErrorClass
# Handle Error
ensure
# Optional block for code that is always executed
end
这种方法比单纯的“rescue”块更可取,因为没有参数的“rescue”会捕获 StandardError 或其任何子类,包括 NameError 和 TypeError。
这是一个例子:
begin
raise "Error"
rescue RuntimeError
puts "Runtime error encountered and rescued."
end
【讨论】: