Kernel#exit
exit(status = 0) -> never returns Returns:
never returns (exits process) · Updated March 13, 2026 · Kernel Methods process exit termination
The exit method terminates the Ruby program immediately. It raises a SystemExit exception which, by default, is not caught, causing the program to terminate.
Syntax
exit
exit(status)
exit(status: code)
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
status | Integer | 0 | The exit status code returned to the operating system. A status of 0 indicates success; non-zero indicates failure. |
Examples
Basic usage
puts "Starting program..."
exit
puts "This will never run"
# Output: Starting program...
Exiting with a status code
begin
file = File.open("data.txt")
rescue Errno::ENOENT
puts "Error: File not found"
exit(1) # Exit with error status
end
# If we reach here, exit with success
exit(0)
Using keyword argument
exit(status: 42)
Common Patterns
Using exit in CLI tools
require 'optparse'
options = {}
OptionParser.new do |opts|
opts.on("-v", "--version", "Show version") do
puts "MyApp version 1.0"
exit(0)
end
end.parse!
Preventing accidental exit
begin
exit(1)
rescue SystemExit => e
puts "Exit attempted with status: #{e.status}"
# Handle gracefully instead of terminating
end
Errors
Calling exit raises a SystemExit exception. If this exception is not caught, the program terminates with the specified status. To prevent termination, you can rescue SystemExit:
begin
exit(1)
rescue SystemExit
puts "Caught exit attempt"
end
puts "Program continues"
# Output: Caught exit attempt
# Output: Program continues