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

Throw and rethrow patterns in C Sharp (C#) - Mini Project: Build & Apply

Choose your learning style9 modes available
Throw and Rethrow Patterns
📖 Scenario: Imagine you are building a simple calculator app that divides two numbers. Sometimes, the user might enter zero as the divisor, which causes an error. You want to catch this error, add a message, and then rethrow it so the program can handle it properly.
🎯 Goal: You will create a program that demonstrates how to throw and rethrow exceptions in C#. This helps you understand how to handle errors and pass them along with extra information.
📋 What You'll Learn
Create a method called Divide that takes two integers numerator and denominator.
Inside Divide, throw a DivideByZeroException if denominator is zero.
Use a try-catch block in Divide to catch the exception, add a message, and rethrow it.
In Main, call Divide and catch the rethrown exception to print its message.
💡 Why This Matters
🌍 Real World
Throwing and rethrowing exceptions is common in real apps to handle errors clearly and pass useful messages up the call chain.
💼 Career
Understanding exception handling is essential for writing robust, maintainable code in professional software development.
Progress0 / 4 steps
1
Create the Divide method with parameters
Create a method called Divide that takes two integer parameters named numerator and denominator. For now, just return 0 inside the method.
C Sharp (C#)
Need a hint?
Define a method named Divide with two int parameters and return an int value.
2
Throw DivideByZeroException if denominator is zero
Inside the Divide method, add an if statement to check if denominator is zero. If it is, throw a new DivideByZeroException with the message "Cannot divide by zero."
C Sharp (C#)
Need a hint?
Use throw new DivideByZeroException with the exact message inside the if block.
3
Catch and rethrow the exception with a message
Modify the Divide method to use a try-catch block. Put the if check and division inside the try. In the catch (DivideByZeroException ex), throw a new DivideByZeroException with the message "Error in Divide method: " plus the original exception message.
C Sharp (C#)
Need a hint?
Use try-catch to catch the exception and rethrow with a new message combining your text and ex.Message.
4
Call Divide in Main and print the exception message
In the Main method, call Divide(10, 0) inside a try-catch block. Catch DivideByZeroException ex and print ex.Message using Console.WriteLine.
C Sharp (C#)
Need a hint?
Use try-catch in Main to call Divide and print the exception message.