Python的Ruby等价物';s";试一试;?
我正在尝试将一些Python代码转换成Ruby。Ruby中是否有与Python中的Python的Ruby等价物';s";试一试;?,python,python-3.x,ruby,try-catch,language-comparisons,Python,Python 3.x,Ruby,Try Catch,Language Comparisons,我正在尝试将一些Python代码转换成Ruby。Ruby中是否有与Python中的try语句等价的语句 begin some_code rescue handle_error ensure this_code_is_always_executed end 详细信息:以此为例: begin # "try" block puts 'I am before the raise.' raise 'An error has occurr
try
语句等价的语句
begin
some_code
rescue
handle_error
ensure
this_code_is_always_executed
end
详细信息:以此为例:
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
begin
raise "Error"
rescue RuntimeError
puts "Runtime error encountered and rescued."
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.')
如果要捕获特定类型的异常,请使用:
begin
# Code
rescue ErrorClass
# Handle Error
ensure
# Optional block for code that is always executed
end
这种方法比裸的“rescue”块更好,因为没有参数的“rescue”将捕获StandardError或其任何子类,包括NameError和TypeError
以下是一个例子:
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
begin
raise "Error"
rescue RuntimeError
puts "Runtime error encountered and rescued."
end
请出示一个密码!查找Ruby
rescue
(和raise
)哦,太棒了!感谢您还提供了一个python示例。我要“试试”它!哈哈!还有一个奇怪的else
子句,只有在没有触发异常的情况下才会执行。这是最简单的答案,也是可以理解的,感谢从形式和内容两个角度给出的最佳答案之一;非常感谢伟大的链接!这真的很有帮助。