Exceptions are a way of handling execution flow when an error occurs. This will show some examples of how to raise and handle exceptions, how to create custom exception classes, and how to detect if no exceptions are raised.
Simple begin/rescue example
rescue will catch any exception. The
raise is creating a generic
exception with no message.
begin raise rescue puts 'Caught an exception!' end
Begin/rescue with more information
This is similar to the previous example except more information is provided in the error handling.
begin raise 'Some error happened!' rescue Exception => e puts 'Caught an exception!' puts e.message puts e.backtrace.inspect end
Create custom exception classes
You can create custom exception classes by inheriting from
Read more about
StandardError at https://ruby-doc.org/core-2.6.3/StandardError.html.
class MyException < StandardError end begin raise MyException.new 'Error!' rescue MyException => e puts e end
Catch multiple exceptions
This is an example of catching different kinds of exceptions. Optionally you can store and reference the exception. Optionally you can have a catch-all case. Optionally you can have an else statement that runs if no rescues happen.
begin raise SomeExceptionClass rescue SomeExceptionClass puts 'Rescued from Some Exception' rescue ThatExceptionClass => e puts 'Rescued from That Exception' puts e rescue puts 'Some other exception caught.' end
Detect when no exceptions are raised
else statement inside a
begin block can be used to execute
code when no exceptions are raised, indiciating the block ran without error.
begin puts 'Working smoothly.' rescue puts 'Error detected.' else puts 'No errors detected' end
This should give you a very basic idea of how to use exceptions in Ruby for error handling.