Ruby Exceptions

Exceptions in Ruby are a type of object that represents an error or an unusual state in your program. When this unusual state occurs, an exception is "raised" (or "thrown"). Your program can then "rescue" (or "catch") the exception and handle it.

Here's a brief overview of exceptions in Ruby:

1. Raising Exceptions:

You can raise an exception in Ruby using the raise keyword:

raise "An error has occurred"

This will stop the execution of your program and print an error message, unless the exception is rescued.

By default, raise creates an exception of the RuntimeError class, but you can specify a different class if you want:

raise StandardError, "An error has occurred"

2. Rescuing Exceptions:

You can rescue an exception using the rescue keyword. This allows you to handle the exception and continue the execution of your program:

begin
  raise "An error has occurred"
rescue
  puts "An error was rescued"
end

This will print "An error was rescued" and continue with the rest of the program.

You can also rescue specific types of exceptions:

begin
  raise "An error has occurred"
rescue RuntimeError
  puts "A RuntimeError was rescued"
rescue StandardError
  puts "A StandardError was rescued"
end

In this example, "A RuntimeError was rescued" will be printed.

3. Ensuring Code is Executed:

The ensure keyword can be used to make sure certain code gets executed, whether an exception is raised or not:

begin
  raise "An error has occurred"
rescue
  puts "An error was rescued"
ensure
  puts "This gets executed no matter what"
end

This will print both "An error was rescued" and "This gets executed no matter what".

4. Raising and then Rescuing:

You can use the raise keyword in a rescue block to raise a new exception. This is often used to raise a more specific or descriptive exception:

begin
  raise "An error has occurred"
rescue
  raise StandardError, "A more specific error has occurred"
end

This will raise the new StandardError and print its message.

Exceptions are a powerful tool in Ruby for handling errors and unusual conditions in your program. Remember, though, that exceptions are for exceptional conditions, and shouldn't be used for normal flow control in your program. Use exceptions when you're dealing with a condition that your program can't handle or wasn't designed to handle.

  1. Handling exceptions in Ruby:

    • Description: Exception handling allows you to gracefully manage errors and unexpected situations in your code.
    • Code example:
      begin
        # Code that may raise an exception
        result = 10 / 0
      rescue => e
        # Handle the exception
        puts "An error occurred: #{e.message}"
      end
      
  2. Ruby raise exception example:

    • Description: The raise keyword allows you to explicitly raise an exception.
    • Code example:
      def check_value(value)
        raise ArgumentError, 'Invalid value' unless value.is_a?(Integer)
      end
      
  3. Rescuing exceptions in Ruby:

    • Description: Use the rescue keyword to catch and handle exceptions.
    • Code example:
      begin
        # Code that may raise an exception
        result = 10 / 0
      rescue ZeroDivisionError
        # Handle a specific exception
        puts 'Cannot divide by zero.'
      rescue => e
        # Handle any other exception
        puts "An error occurred: #{e.message}"
      end
      
  4. Custom exceptions in Ruby:

    • Description: You can define custom exception classes for specific error scenarios.
    • Code example:
      class CustomError < StandardError
      end
      
      raise CustomError, 'This is a custom error.'
      
  5. Raising specific exceptions in Ruby:

    • Description: Choose the appropriate exception type when raising exceptions for specific error scenarios.
    • Code example:
      def check_value(value)
        raise ArgumentError, 'Invalid value' unless value.is_a?(Integer)
      end
      
  6. Ruby ensure block with exceptions:

    • Description: The ensure block contains code that will be executed whether an exception is raised or not.
    • Code example:
      begin
        # Code that may raise an exception
        result = perform_operation
      rescue => e
        # Handle the exception
        puts "An error occurred: #{e.message}"
      ensure
        # Ensure this code always runs
        cleanup_resources
      end
      
  7. Global exception handling in Ruby:

    • Description: Use at_exit to set up a global exception handler for unhandled exceptions.
    • Code example:
      at_exit do
        # Global exception handler
        puts "Unhandled exception: #{ $! }" if $!
      end
      
  8. Ruby catch and throw vs. exceptions:

    • Description: catch and throw provide a non-exceptional mechanism for breaking out of nested loops or methods.
    • Code example:
      catch(:my_label) do
        # Code block
        throw :my_label if some_condition
      end