raise
raise sounds the alarm on purpose when your code finds a problem it cannot fix. It is like shouting 'stop, something is wrong!'.
In this page:
Syntax
raise "message"
raise ExceptionType, "message"
raise # re-raise current exception
raise
raise triggers an exception explicitly, either a new one with a message (raise "something broke") or a specific exception class (raise ArgumentError, "bad input").
Calling raise with no arguments inside a rescue block re-raises the currently caught exception. Methods that detect invalid input or state typically raise rather than silently returning an error value.
Note:
Bare
raise (no arguments) inside a rescue block re-raises the exception currently being handled, preserving its original details.Example: raise
def check_age(age)
raise ArgumentError, "Age cannot be negative" if age < 0
puts "Age #{age} is valid"
end
begin
check_age(-5)
rescue ArgumentError => e
puts "Error: #{e.message}"
end
Login to try C/C++/Java/PHP code in the editor
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Writing
raisewith only a class and a message in the wrong order, as inraise "msg", ArgumentError. - Rescuing and re-raising without a message, hiding why it failed.
- Using
raiseas areturn, when it stops the method unless rescued.
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: