Python の「try」に相当する Ruby はありますか? 質問する

Python の「try」に相当する Ruby はありますか? 質問する

Python コードを Ruby に変換しようとしています。Pythontryのステートメントに相当するものが Ruby にありますか?

ベストアンサー1

これを例として挙げます:

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 StandardError => 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.')

おすすめ記事