Try and Except in ruby

0

I'm learning how to program in ruby, my main language is python, so I was hesitant if there is any equivalent to try and except for python in ruby:

try:
    print("No hubo errores")
except:
    print("Si hubo errores")

Is there something similar or equal in ruby?

Many thanks to those who take the time to answer this: 3

    
asked by binario_newbie 10.07.2018 в 18:09
source

1 answer

2

Yes, you can use begin / rescue / ensure / end 1 ; for example:

begin
  # código que puede generar error
  puts "No hubo errores"
rescue
  # este código se ejecuta únicamente si el código en 'begin' arroja una excepción
  puts "Sí hubo errores"
ensure
  # este código se ejecuta siempre, sin importar si se arroja una excepción.
end

When you use rescue it is recommended to catch the specific exception that your code can generate or, in the worst case, catch StandardError :

begin
  # ...
rescue StandardError => e
  puts Error: "e.description"
end

1 Both rescue and ensure are optional.

    
answered by 10.07.2018 / 18:30
source