Ad space (banner)
๐Ÿ’ŽRuby Lessons
Lesson 10 / 68

Error Handling (begin...rescue)

In this lesson you will learn error handling in Ruby with begin...rescue, so an unexpected failure does not bring your whole program down. This is for anyone searching for "Ruby begin rescue how to use".

raise raises an exception and begin / rescue catches it. It works like insurance: you decide in advance what to do if something goes wrong.

The sample code raises an exception inside divide with raise "cannot divide by zero" if b == 0 when asked to divide by zero. Placing the if at the end - a "trailing if" - is another piece of concise, idiomatic Ruby.

A common stumbling block for beginners is that begin can be omitted inside a method. That shorter form keeps error handling simple, but until you are used to it you may find yourself hunting for where the begin went.

An exception object has a message method that gives the details of the error. Writing rescue => e receives the exception as e so you can inspect it.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Ruby directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)