Exception Handling (begin-rescue)

💎 Ruby Lesson 14 Advanced

Exceptions are runtime errors. Ruby captures exceptions using begin-rescue blocks, keeping applications running smoothly when errors occur.

1 begin, rescue, and ensure execution cycles

Ruby exception handling uses its own naming syntax:

  • begin: Wraps code blocks that may fail.
  • rescue: Catches thrown errors (equivalent of catch).
  • ensure: Executes cleanup code, running regardless of whether an error was raised (equivalent of finally).
  • raise: Manually triggers exceptions.
2 Exceptions Code

Let's run a program handling a division-by-zero error using rescue blocks:

Ruby — Exceptions ▶ Run Code
begin
  x = 10
  y = 0
  result = x / y # Throws ZeroDivisionError
rescue ZeroDivisionError => e
  puts "Error Intercepted: division by zero is invalid."
  puts "Details: #{e.message}"
ensure
  puts "Ensure block executed. Cleaning up streams..."
end

puts "Program execution continues smoothly..."
3 Code Challenge
Challenge: Write a custom method that raises an `ArgumentError` if an input parameter score is outside the range 0-100. Write a begin-rescue block to call this method with an invalid argument and handle the error.