Ruby try-except alternative?

days_64

Python64

Posted on February 27, 2020

Ruby try-except alternative?

Do you know the idea of try-catch or try-except?

This is used to handle errors that occur during the execution of a program. Errors can happen anytime, like file can't be opened or out of memory error.

Your program shouldn't crash if that happens, so the try-catch or try-except block is used.

Try-except in other languages

The concept isn't unique to one programming language. Many programming language support this structure.

In C++, there's this code sequence, where try does the statements and catch handles the faults:

try {
   // ...
} catch (...) {
   // ...
}

In Python, you can use try-except-finally. Here try executes statements, except catches possible exceptions and finally always is run. So like this:

try:
    # try block
except:  
    # catch exception
finally: 
    # will always get executed

Ruby try-catch

But what about the Ruby programming language?

Ruby is somewhat similar to Python, but it's different in a variety of ways.

Although I like the idea of try-except, Ruby doesn't have the traditional try-catch or try-except code block, instead it uses a begin-end sequence that works similarly:

begin
     some_code
rescue
     handle_error  
ensure 
    this_code_is_always_executed
end

Here is an example:

begin
    raise "Error"
rescue RuntimeError
    puts "Runtime error encountered and rescued."
end

Another example:

begin  # "try" block
    puts 'I am before the raise.'  
    raise 'An error has occured.' # 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 
💖 💪 🙅 🚩
days_64
Python64

Posted on February 27, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related