How to Use raise in Ruby: Syntax and Examples
In Ruby, use
raise to trigger an exception and stop normal program flow. You can raise a generic error with raise or specify an error type and message like raise RuntimeError, 'message'.Syntax
The raise keyword is used to trigger an exception. You can use it in three main ways:
raise- raises a generic RuntimeError with no message.raise "message"- raises a RuntimeError with a custom message.raise ExceptionClass, "message"- raises a specific exception type with a message.
ruby
raise raise "Something went wrong" raise ArgumentError, "Invalid argument"
Example
This example shows how to use raise to stop execution when a condition is not met, and how to rescue the error to handle it gracefully.
ruby
def check_age(age) raise ArgumentError, "Age must be 18 or older" if age < 18 "Access granted" end begin puts check_age(20) # This will print "Access granted" puts check_age(16) # This will raise an error rescue ArgumentError => e puts "Error: #{e.message}" end
Output
Access granted
Error: Age must be 18 or older
Common Pitfalls
Common mistakes when using raise include:
- Raising without a message, which can make debugging harder.
- Raising the wrong exception type for the error situation.
- Not rescuing exceptions when needed, causing the program to crash unexpectedly.
Always provide meaningful messages and use appropriate exception classes.
ruby
def divide(a, b) # Wrong: no message # raise if b == 0 # Better: raise with message and exception type raise ZeroDivisionError, "Cannot divide by zero" if b == 0 a / b end
Quick Reference
| Usage | Description |
|---|---|
| raise | Raises a RuntimeError with no message |
| raise "message" | Raises a RuntimeError with a custom message |
| raise ExceptionClass, "message" | Raises a specific exception type with a message |
| raise e | Re-raises the current exception object e |
Key Takeaways
Use
raise to trigger exceptions and stop normal program flow in Ruby.Provide clear messages and use specific exception classes for better error handling.
Rescue exceptions when you want to handle errors gracefully and prevent crashes.
Avoid raising exceptions without messages to make debugging easier.
Use
raise inside methods to enforce conditions and signal problems.