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

Finally block behavior in C Sharp (C#) - Mini Project: Build & Apply

Choose your learning style9 modes available
Finally Block Behavior
📖 Scenario: Imagine you are writing a program that reads a number from a list and divides 100 by that number. Sometimes the number might be zero, which causes an error. You want to make sure that no matter what happens, a message is always shown to say the operation is complete.
🎯 Goal: You will create a program that uses a try, catch, and finally block to handle division by zero errors and always print a completion message.
📋 What You'll Learn
Create an integer array called numbers with the values 10, 0, and 5
Create an integer variable called index and set it to 1
Use a try block to divide 100 by numbers[index] and store the result in result
Use a catch block to catch DivideByZeroException and print "Cannot divide by zero."
Use a finally block to print "Operation complete."
Print the result if no exception occurs
💡 Why This Matters
🌍 Real World
Handling errors safely is important in real programs to avoid crashes and to clean up resources.
💼 Career
Understanding <code>try-catch-finally</code> blocks is essential for writing robust C# applications in many software development jobs.
Progress0 / 4 steps
1
Create the numbers array
Create an integer array called numbers with the values 10, 0, and 5.
C Sharp (C#)
Need a hint?

Use int[] numbers = {10, 0, 5}; to create the array.

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

Use int index = 1; to set the index.

3
Add try, catch, and finally blocks
Write a try block that divides 100 by numbers[index] and stores the result in an integer variable called result. Add a catch block to catch DivideByZeroException and print "Cannot divide by zero.". Add a finally block that prints "Operation complete.".
C Sharp (C#)
Need a hint?

Use try, catch (DivideByZeroException), and finally blocks as shown.

4
Print the result
Add a line to print the value of result after the try-catch-finally blocks.
C Sharp (C#)
Need a hint?

Use Console.WriteLine(result); to print the result.