Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Raising Exceptions in Ruby
2.1.
Raising Generic Exceptions
3.
Raising Custom Exceptions
4.
Frequently Asked Questions
4.1.
Does raising an exception stop execution of Ruby?
4.2.
How do you raise in Ruby?
4.3.
How do you handle exceptions in Ruby?
4.4.
How do you add exceptions to Ruby?
4.5.
Does raise return Ruby?
5.
Conclusion
Last Updated: Mar 27, 2024

Raising Exceptions with "raise" in Ruby

Author GAZAL ARORA
0 upvote

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: "

Raising Custom Exceptions

Some pointers:

  1. Any custom Ruby exception should extend StandardError rather than the Exception class (the reason for this is outlined in Exception Handling in Ruby). 
  2. To define a custom error message or pass additional data along with your custom error, we need to simply override the constructor to accept custom parameters.

 

The following class definition allows us to raise our own custom exception with the additional data:

class MyCustomException < StandardError
  def initialize(msg="This is my custom exception", exception_type="custom")
    @exception_type = exception_type
    super(msg)
  end
end
You can also try this code with Online Java Compiler
Run Code

 

Using the above class in the code

begin
    raise MyCustomException.new "Message, message, message", "Yup"
rescue MyCustomException => e
    puts e.message *# Message, message, message*
    puts e.exception_type *# Yup*
end
You can also try this code with Online Java Compiler
Run Code

Frequently Asked Questions

Does raising an exception stop execution of Ruby?

We raise an exception in the case whenever the code encounters any conditions that prevent further execution. Therefore, raising exceptions will raise an issue and stop further execution.

How do you raise in Ruby?

By calling Kernel#raise, Ruby allows you to raise exceptions manually. This allows you to specify your error message and the kind of Exception you want to raise. Ruby will raise a RuntimeError by default if you do not specify the type of Exception to raise (a subclass of StandardError).

How do you handle exceptions in Ruby?

An additional exception class known as the Exception class, which contains several types of methods, is also provided by Ruby. The code in which it is raised is included within the begin/end block so that you can use a rescue clause to handle this kind of exception.

How do you add exceptions to Ruby?

Classes are used for everything in Ruby, even exceptions. Simply construct a class that inherits from StandardError or one of its offspring to generate a new type of exception. New exceptions typically have class names that end in "Error."

Does raise return Ruby?

Ruby will re-raise the original rescued exception if you call raise without any parameters while inside a rescue block.

Conclusion

In this article, we learned about Raising Exceptions with "raise" in Ruby. Starting from learning to raise standard exceptions, we concluded by learning to raise our custom exceptions.

I hope you like it. If you wish to learn more about Ruby, check out our articles on Tainting Objects in RubyObject Marshalling in RubyHow To Invoke Global Functions In Ruby?Copying Objects In Ruby, and Object References in Ruby.

Refer to our Guided Path on Coding Ninjas Studio to upskill yourself in Competitive ProgrammingData Structures and AlgorithmsJavaScriptSystem Design, and many more! To test your competency in coding, you can check out the mock test series and participate in various contests hosted on Coding Ninjas Studio! 

Do upvote if you find our blogs helpful and engaging!

Happy Coding!

Live masterclass