← Back to Ruby Course | Chapter 11: File I/O & Exceptions | Lesson 4 of 6

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:

  1. raise
Syntax
ruby
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

markup
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
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
  1. Writing raise with only a class and a message in the wrong order, as in raise "msg", ArgumentError.
  2. Rescuing and re-raising without a message, hiding why it failed.
  3. Using raise as a return, when it stops the method unless rescued.
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.