0
0
Rubyprogramming~30 mins

Exception hierarchy in Ruby - Mini Project: Build & Apply

Choose your learning style9 modes available
Exception hierarchy
📖 Scenario: Imagine you are building a simple program that handles different types of errors. You want to organize these errors in a clear way so your program can respond properly when something goes wrong.
🎯 Goal: You will create a small exception hierarchy with a base error class and two specific error classes. Then, you will raise and rescue these errors to see how the hierarchy works.
📋 What You'll Learn
Create a base exception class called MyAppError that inherits from StandardError.
Create two subclasses called DatabaseError and NetworkError that inherit from MyAppError.
Write code to raise a DatabaseError exception.
Write code to rescue the exception using the base class MyAppError and print a message.
💡 Why This Matters
🌍 Real World
Organizing errors in a clear hierarchy helps large programs handle problems gracefully and makes debugging easier.
💼 Career
Understanding exception hierarchies is important for writing robust software and is a common skill required in software development jobs.
Progress0 / 4 steps
1
Create the base exception class
Create a class called MyAppError that inherits from StandardError.
Ruby
Need a hint?

Use class MyAppError < StandardError to create the base exception class.

2
Create subclasses for specific errors
Create two classes called DatabaseError and NetworkError that inherit from MyAppError.
Ruby
Need a hint?

Define each subclass with class ClassName < MyAppError.

3
Raise a DatabaseError exception
Write code to raise a DatabaseError exception with the message "Database connection failed".
Ruby
Need a hint?

Use raise DatabaseError, "Database connection failed" to raise the exception.

4
Rescue the exception and print a message
Wrap the code that raises the DatabaseError inside a begin block. Rescue the exception using MyAppError and print "Caught an error: " followed by the exception message.
Ruby
Need a hint?

Use begin and rescue MyAppError => e to catch the error and puts to print the message.