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

Multiple catch blocks in C Sharp (C#) - Mini Project: Build & Apply

Choose your learning style9 modes available
Handling Errors with Multiple Catch Blocks in C#
📖 Scenario: Imagine you are writing a simple calculator program that divides two numbers. Sometimes, users might enter zero as the divisor or enter invalid input. You want to handle these errors gracefully.
🎯 Goal: Build a C# program that uses try with multiple catch blocks to handle different types of errors separately.
📋 What You'll Learn
Create two integer variables named numerator and denominator with exact values.
Create a try block to perform division.
Add two catch blocks: one for DivideByZeroException and one for FormatException.
Print the result or error messages accordingly.
💡 Why This Matters
🌍 Real World
Handling errors gracefully is important in real-world programs to avoid crashes and give users helpful messages.
💼 Career
Understanding multiple catch blocks is essential for writing robust C# applications that handle different error types properly.
Progress0 / 4 steps
1
Create numerator and denominator variables
Create two integer variables called numerator and denominator with values 10 and 0 respectively.
C Sharp (C#)
Need a hint?

Use int numerator = 10; and int denominator = 0; to create the variables.

2
Add a try block to divide numerator by denominator
Add a try block that attempts to divide numerator by denominator and stores the result in an integer variable called result.
C Sharp (C#)
Need a hint?

Use try { int result = numerator / denominator; } to catch errors during division.

3
Add multiple catch blocks for DivideByZeroException and FormatException
Add two catch blocks after the try: one catching DivideByZeroException that prints "Cannot divide by zero.", and another catching FormatException that prints "Invalid input format.".
C Sharp (C#)
Need a hint?

Use two separate catch blocks for each exception type with the exact messages.

4
Print the result if division succeeds
Inside the try block, after dividing, add a Console.WriteLine to print "Result: " followed by the result variable.
C Sharp (C#)
Need a hint?

Use Console.WriteLine("Result: " + result); inside the try block.