0
0
RubyHow-ToBeginner · 3 min read

How to Create Custom Exception in Ruby: Simple Guide

In Ruby, you create a custom exception by defining a new class that inherits from StandardError or another built-in exception class. This lets you raise and rescue your own error types using raise and rescue.
📐

Syntax

To create a custom exception, define a class that inherits from StandardError. This class can be empty or include custom methods.

  • class: defines the new exception class.
  • StandardError: the base class for most Ruby exceptions.
  • Use raise to trigger the exception.
ruby
class MyCustomError < StandardError
end
💻

Example

This example shows how to define a custom exception, raise it, and handle it with rescue.

ruby
class MyCustomError < StandardError
end

def test_error(value)
  raise MyCustomError, "Value cannot be zero" if value == 0
  "Value is #{value}"
end

begin
  puts test_error(10)
  puts test_error(0)
rescue MyCustomError => e
  puts "Caught a custom error: #{e.message}"
end
Output
Value is 10 Caught a custom error: Value cannot be zero
⚠️

Common Pitfalls

Common mistakes include inheriting from Exception directly, which is not recommended because it catches system errors. Also, forgetting to rescue your custom exception can cause your program to crash unexpectedly.

Always inherit from StandardError unless you have a specific reason.

ruby
class WrongError < Exception
end

class RightError < StandardError
end
📊

Quick Reference

ConceptDescription
class MyError < StandardErrorDefines a custom exception class
raise MyError, "message"Raises the custom exception with a message
rescue MyError => eCatches the custom exception and stores it in variable e
StandardErrorRecommended base class for custom exceptions
ExceptionAvoid inheriting directly unless necessary

Key Takeaways

Create custom exceptions by inheriting from StandardError.
Use raise to trigger and rescue to handle your custom exceptions.
Avoid inheriting directly from Exception to prevent catching system errors.
Provide clear error messages when raising exceptions.
Always rescue your custom exceptions to handle errors gracefully.