0
0
Rubyprogramming~5 mins

Raise for throwing errors in Ruby

Choose your learning style9 modes available
Introduction

We use raise to stop the program when something goes wrong. It helps us find and fix errors quickly.

When a function gets wrong or unexpected input.
When a file or resource is missing.
When a calculation or operation cannot continue safely.
When you want to tell the user or developer about a problem clearly.
Syntax
Ruby
raise
raise "Error message"
raise SomeErrorClass, "Error message"

raise without arguments re-raises the last error.

You can give a message to explain the error.

Examples
Stops the program and shows the last error again.
Ruby
raise
Stops the program and shows this message.
Ruby
raise "Something went wrong!"
Stops the program with a specific error type and message.
Ruby
raise ArgumentError, "Invalid argument"
Sample Program

This program divides two numbers. It uses raise to stop if the second number is zero, because dividing by zero is not allowed.

Ruby
def divide(a, b)
  raise ArgumentError, "Cannot divide by zero" if b == 0
  a.to_f / b
end

puts divide(10, 2)
puts divide(5, 0)
OutputSuccess
Important Notes

Use raise to make your program safer and easier to debug.

Custom error messages help others understand what went wrong.

Summary

raise stops the program when an error happens.

You can add messages or error types to explain the problem.

It helps catch mistakes early and keep your program reliable.