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

Exception hierarchy in .NET in C Sharp (C#) - Mini Project: Build & Apply

Choose your learning style9 modes available
Exception hierarchy in .NET
📖 Scenario: Imagine you are building a simple program that processes user input and might encounter different types of errors. You want to understand how exceptions are organized in .NET so you can handle them properly.
🎯 Goal: You will create a small program that defines a few exceptions following the .NET exception hierarchy and demonstrates catching them in order.
📋 What You'll Learn
Create a base exception class called MyAppException that inherits from System.Exception.
Create two derived exception classes: InputException and ProcessingException that inherit from MyAppException.
Write a method ProcessInput that throws InputException if input is empty and ProcessingException if input is "error".
Use a try-catch block to catch exceptions in order: first InputException, then ProcessingException, then MyAppException, and finally Exception.
💡 Why This Matters
🌍 Real World
Understanding exception hierarchy helps you write robust programs that can handle errors clearly and maintainably.
💼 Career
Many software development jobs require good error handling skills to build reliable applications.
Progress0 / 4 steps
1
Create base exception class
Create a class called MyAppException that inherits from System.Exception and has a constructor that takes a string message and passes it to the base constructor.
C Sharp (C#)
Need a hint?

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

2
Create derived exception classes
Create two classes called InputException and ProcessingException that both inherit from MyAppException. Each should have a constructor that takes a string message and passes it to the base constructor.
C Sharp (C#)
Need a hint?

Both classes inherit from MyAppException and call the base constructor with the message.

3
Write method that throws exceptions
Write a static method called ProcessInput that takes a string input. If input is empty, throw an InputException with message "Input is empty". If input is "error", throw a ProcessingException with message "Processing error occurred". Otherwise, do nothing.
C Sharp (C#)
Need a hint?

Use string.IsNullOrEmpty(input) to check for empty input and throw the correct exceptions.

4
Catch exceptions in order
In the Main method, call ProcessInput three times with inputs: empty string, "error", and "ok". Use a try-catch block to catch exceptions in this order: InputException, ProcessingException, MyAppException, and Exception. Print the caught exception's message with Console.WriteLine. If no exception occurs, print "Input processed successfully".
C Sharp (C#)
Need a hint?

Remember to catch exceptions from most specific to most general. Print the exception message or success message accordingly.