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

When clause in catch in C Sharp (C#) - Mini Project: Build & Apply

Choose your learning style9 modes available
Handling Exceptions with When Clause in Catch
📖 Scenario: Imagine you are writing a program that processes user input numbers. Sometimes, the input might cause errors like division by zero or invalid format. You want to catch these errors but handle them differently based on the error details.
🎯 Goal: You will create a program that uses try-catch blocks with when clauses to catch exceptions only when certain conditions are met.
📋 What You'll Learn
Create a variable called numbers with the values 10, 0, and 5.
Create a variable called index and set it to 1.
Use a try block to divide 100 by the number at numbers[index].
Use a catch block with a when clause to catch DivideByZeroException only when the exception message contains the word zero.
Use another catch block with a when clause to catch IndexOutOfRangeException only when index is greater than 2.
Print the appropriate messages inside each catch block.
Print "Division result: {result}" if no exception occurs.
💡 Why This Matters
🌍 Real World
In real programs, you often need to handle errors carefully depending on the exact problem. Using <code>when</code> clauses helps you write cleaner and more precise error handling.
💼 Career
Understanding advanced exception handling is important for writing robust software that can handle unexpected situations gracefully, a key skill for software developers.
Progress0 / 4 steps
1
Create the initial data variables
Create a list of integers called numbers with the values 10, 0, and 5.
C Sharp (C#)
Need a hint?

Use an array of integers with the exact values given.

2
Add the index variable
Create an integer variable called index and set it to 1.
C Sharp (C#)
Need a hint?

Declare index as an integer and assign it the value 1.

3
Add try block with division
Add a try block that divides 100 by numbers[index] and stores the result in an integer variable called result.
C Sharp (C#)
Need a hint?

Use a try block and perform the division inside it.

4
Add catch blocks with when clauses and output
Add a catch block for DivideByZeroException with a when clause that checks if ex.Message.Contains("zero"). Inside it, print "Cannot divide by zero!". Add another catch block for IndexOutOfRangeException with a when clause that checks if index > 2. Inside it, print "Index is out of range!". Finally, if no exception occurs, print "Division result: {result}".
C Sharp (C#)
Need a hint?

Use catch (DivideByZeroException ex) when (ex.Message.Contains("zero")) and print the message. Use catch (IndexOutOfRangeException) when (index > 2) and print the other message. Print the result if no exception.