0
0
C Sharp (C#)programming~30 mins

Custom exception classes in C Sharp (C#) - Mini Project: Build & Apply

Choose your learning style9 modes available
Custom Exception Classes in C#
📖 Scenario: Imagine you are building a simple banking application. You want to handle errors clearly when someone tries to withdraw more money than they have in their account.
🎯 Goal: You will create a custom exception class called InsufficientFundsException to represent this specific error. Then, you will use this exception in a method that withdraws money from an account.
📋 What You'll Learn
Create a custom exception class named InsufficientFundsException that inherits from Exception.
Add a constructor to InsufficientFundsException that takes a string message and passes it to the base Exception class.
Create a variable balance of type decimal with the value 1000m.
Create a variable withdrawAmount of type decimal with the value 1500m.
Write an if statement to check if withdrawAmount is greater than balance and throw InsufficientFundsException with the message "Not enough money in the account.".
Write a try-catch block to catch InsufficientFundsException and print the exception message.
💡 Why This Matters
🌍 Real World
Custom exceptions help you handle specific errors in your programs clearly, like when a bank account has insufficient funds.
💼 Career
Understanding custom exceptions is important for writing robust, maintainable code in professional software development.
Progress0 / 4 steps
1
Create the custom exception class
Create a public class called InsufficientFundsException that inherits from Exception. Add a constructor that takes a string parameter message and passes it to the base Exception constructor using base(message).
C Sharp (C#)
Need a hint?

Remember to inherit from Exception and call the base constructor with the message.

2
Set up account balance and withdrawal amount
Create a decimal variable called balance and set it to 1000m. Create another decimal variable called withdrawAmount and set it to 1500m.
C Sharp (C#)
Need a hint?

Use decimal type and remember the m suffix for decimal literals.

3
Throw the custom exception when withdrawal is too large
Inside the Main method, write an if statement that checks if withdrawAmount is greater than balance. If true, throw a new InsufficientFundsException with the message "Not enough money in the account.".
C Sharp (C#)
Need a hint?

Use throw new InsufficientFundsException("message") inside the if block.

4
Catch and display the custom exception message
Wrap the if statement inside a try block. Add a catch block that catches InsufficientFundsException as ex and prints ex.Message using Console.WriteLine.
C Sharp (C#)
Need a hint?

Use try and catch (InsufficientFundsException ex) to handle the exception and print ex.Message.