Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

Ruby Dictionary

  1. Home
  2. Ruby Dictionary
  3. begin / rescue / ensure / raise

begin / rescue / ensure / raise

The basic syntax for exception handling. Use begin to wrap code that may raise an exception, rescue to handle it, and ensure to run cleanup code.

Syntax

# Basic exception handling syntax.
begin
  # Code that may raise an exception
rescue ExceptionClass => e
  # Code to run when an exception is raised
ensure
  # Code that always runs, with or without an exception
end

# Handling multiple exception types.
begin
  # Code
rescue TypeError => e
  # Handle type error
rescue ArgumentError => e
  # Handle argument error
rescue => e
  # Handle any other error (all subclasses of StandardError)
end

# Raise an exception intentionally.
raise "Error message"
raise RuntimeError, "Error message"

Keyword Reference

KeywordDescription
beginStarts a block of code that may raise an exception.
rescueDefines code to run when the specified exception class is raised.
ensureDefines code that always runs at the end, regardless of whether an exception occurred.
raiseRaises an exception intentionally.
retryRestarts execution from the begin block after an exception.
elseDefines code to run when no exception is raised.

Sample Code

# Basic exception handling.
begin
  puts 10 / 0
rescue ZeroDivisionError => e
  puts "Error: #{e.message}"
end

# Use ensure to reliably release resources.
file = nil
begin
  file = File.open("nonexistent_file.txt", "r")
rescue Errno::ENOENT => e
  puts "File not found: #{e.message}"
ensure
  file&.close
  puts "Cleanup complete."
end

# Implement retry logic with a limit.
attempts = 0
begin
  attempts += 1
  puts "Attempt: #{attempts}"
  raise "Temporary error" if attempts < 3
  puts "Succeeded."
rescue RuntimeError => e
  puts "Error: #{e.message}"
  retry if attempts < 3
  puts "Retry limit reached."
end

Notes

Ruby exception handling follows the begin/rescue/ensure/end structure. You can specify multiple rescue clauses; they are evaluated top to bottom and the first matching class is applied. Omitting the exception class catches all subclasses of StandardError.

Use ensure to reliably close resources such as database connections, files, and network connections. When using retry, always set a maximum retry count to prevent an infinite loop. Inside a method definition, you can omit begin and write rescue directly.

If you find any errors or copyright issues, please .