Exceptions in Ruby Language

Exceptions in Ruby Language

Exception handling is a crucial aspect of any programming language, and Ruby is no exception (pun intended). In

Ruby, exceptions provide a way to deal with unexpected errors and ensure that your program doesn’t crash abruptly. In this post, we’ll dive into the world of exceptions in Ruby, understand how they work, and explore how to handle them gracefully with some practical examples.

What is an Exception in Ruby Language?

In Ruby, an exception is an object that represents an exceptional condition, such as a runtime error, that can disrupt the normal flow of a program. Exceptions allow you to handle errors in a structured manner, preventing your program from terminating unexpectedly.

Types of Exceptions in Ruby Language

Ruby has a wide range of built-in exceptions, each serving a specific purpose. Here are some common exceptions:

  1. SyntaxError: Occurs when there is a problem with the syntax of your code.
  2. NameError: Raised when you reference an undefined variable or method.
  3. NoMethodError: Raised when an undefined method is called.
  4. ZeroDivisionError: Occurs when you attempt to divide a number by zero.
  5. ArgumentError: Raised when the wrong number of arguments are passed to a method.

Exception Handling in Ruby Language

To handle exceptions in Ruby, you use a combination of begin, rescue, else, and ensure blocks. Here’s a basic structure:

begin
  # Code that may raise an exception
rescue SomeException => e
  # Handle the exception
else
  # Code to run when no exception occurs
ensure
  # Code to run regardless of whether an exception was raised
end

Let’s explore this with a practical example:

begin
  result = 10 / 0
rescue ZeroDivisionError => e
  puts "Error: #{e.message}"
else
  puts "No error occurred."
ensure
  puts "Ensuring this code always runs."
end

In this example, a ZeroDivisionError is raised when attempting to divide by zero. The code inside the rescue block handles the exception, and the code in the ensure block runs no matter what, ensuring proper resource cleanup or finalization.

Custom Exceptions in Ruby Language

In addition to the built-in exceptions, you can create custom exceptions to handle specific error conditions in your application. To create a custom exception, you define a new class that inherits from the Exception class or its subclasses.

class MyCustomError < StandardError
  def initialize(msg = "This is a custom error.")
    super
  end
end

begin
  raise MyCustomError, "Something went wrong!"
rescue MyCustomError => e
  puts "Custom Error: #{e.message}"
end

Discover more from PiEmbSysTech

Subscribe to get the latest posts sent to your email.

Leave a Reply

Scroll to Top

Discover more from PiEmbSysTech

Subscribe now to keep reading and get access to the full archive.

Continue reading