multiverse-team-11 / inventory-app

https://inventory-app-11-1emn.onrender.com/
0 stars 2 forks source link

Exception Handling #84

Closed Hannah0701 closed 3 weeks ago

Hannah0701 commented 1 month ago

Construct programs that gracefully handles errors.

Understand how to handle errors using try-catch blocks. Learn about raising and handling custom exceptions.

Hannah0701 commented 3 weeks ago

In Ruby, error handling is done using begin, rescue, else, ensure, and end keywords. These are similar to the try-catch blocks in other languages.

Here's an example of a simple error handling:

begin
  # Code that might raise an exception
  1 / 0
rescue ZeroDivisionError => e
  puts "Error: #{e.message}"
end

In this example, if an error of type ZeroDivisionError occurs in the begin block, the rescue block will be executed.

You can also handle multiple types of errors:

begin
  # Code that might raise an exception
  1 / 0
rescue ZeroDivisionError => e
  puts "Error: #{e.message}"
rescue TypeError => e
  puts "Error: #{e.message}"
end

The ensure block is always executed, whether an exception is raised or not:

begin
  # Code that might raise an exception
  1 / 0
rescue ZeroDivisionError => e
  puts "Error: #{e.message}"
ensure
  puts "This code runs no matter what"
end

You can also define your own custom exceptions by creating a new class that inherits from StandardError:

class MyCustomError < StandardError; end

begin
  # Code that might raise an exception
  raise MyCustomError, "This is a custom error"
rescue MyCustomError => e
  puts "Error: #{e.message}"
end

In this example, MyCustomError is a custom exception class. The raise keyword is used to raise an exception.