0
0
Rubyprogramming~30 mins

Custom exception classes in Ruby - Mini Project: Build & Apply

Choose your learning style9 modes available
Custom exception classes
📖 Scenario: Imagine you are building a simple banking system. You want to handle errors like withdrawing too much money or depositing invalid amounts in a clear way.
🎯 Goal: You will create custom exception classes to represent specific banking errors, then use them to raise and catch errors in your code.
📋 What You'll Learn
Create custom exception classes inheriting from StandardError
Raise custom exceptions with meaningful messages
Rescue and handle the custom exceptions
Print the error messages when exceptions occur
💡 Why This Matters
🌍 Real World
Custom exceptions help make error handling clearer and more specific in real applications like banking systems, improving user experience and debugging.
💼 Career
Understanding how to create and use custom exceptions is important for writing robust, maintainable code in many programming jobs.
Progress0 / 4 steps
1
Create custom exception classes
Create two custom exception classes called InsufficientFundsError and InvalidDepositError that both inherit from StandardError.
Ruby
Need a hint?

Use class ClassName < StandardError to create a custom exception class.

2
Set up account balance variable
Create a variable called balance and set it to 100 to represent the starting money in the account.
Ruby
Need a hint?

Just write balance = 100 to set the starting amount.

3
Raise exceptions based on conditions
Write a method called withdraw that takes an amount parameter. Inside the method, raise InsufficientFundsError with the message "Not enough money" if amount is greater than balance. Also write a method called deposit that raises InvalidDepositError with the message "Deposit must be positive" if amount is less than or equal to zero.
Ruby
Need a hint?

Use raise ExceptionClass, "message" if condition inside the methods.

4
Rescue exceptions and print messages
Call withdraw(150) and deposit(-20) inside begin blocks. Rescue InsufficientFundsError and InvalidDepositError separately, printing their error messages with puts.
Ruby
Need a hint?

Use begin ... rescue ExceptionClass => e ... puts e.message ... end to catch and print errors.