Introduction
Ruby is a dynamic, open-source programming language focused on simplicity and productivity. It has natural-to-read and easy-to-write syntax.
Rescuing pre-defined exceptions is one thing, but it's also important to know how to create and raise your own if you want to use exceptions in your application more effectively.
Raising Exceptions in Ruby
An exception is defined as an unwanted or unexpected event that occurs at runtime or during a program's execution and prevents the instructions from proceeding normally. Regarding handling exceptions, the code between the begin and end blocks is entirely secure, and the rescue block informs Ruby of the sort of Exception that needs to be handled.
Every Exception in Ruby is built from the built-in Exception class, which has many built-in methods, the most popular of which is the message.
By using the raise statement, we can raise a manual user-defined exception. For example, an ATM transaction program raises an exception when the user enters an invalid account number or PIN to withdraw.
Syntax:
raise exception-type "exception message" condition
Raising Generic Exceptions
The raise method in Ruby can be used to raise exceptions. Although a blank exception can be raised, most exceptions come with a message that provides further details about the mistake.
Note: Whenever the raise statement is raised, the rescue is called, and execution begins. RuntimeError is by default raised by the raise statement.
For example, RuntimeError exception can be raised with a custom error message:
raise "This is the error message."
It is possible to raise an instance of an Exception class, such as StandardError:
raise StardardError.new "This is an exception with the error message: "
Note: Exception exceptions are not meant to be rescued, but StandardError exceptions are. This means that if you raise a new Exception instance, you won't be able to rescue it without explicitly rescuing every top-level Exception instance, which may lead to unexpected issues later.
raise Exception.new "This is an exception with the error message: "