Which of the following best explains why exception handling is important in C# programs?
Think about what happens when something unexpected goes wrong during a program's run.
Exception handling allows a program to catch errors and respond to them gracefully, preventing crashes and allowing the program to continue or close safely.
What will be the output of this C# code?
using System; class Program { static void Main() { int[] numbers = {1, 2, 3}; Console.WriteLine(numbers[5]); Console.WriteLine("End of program"); } }
Think about what happens when you try to access an array index that does not exist.
Accessing an invalid index causes an exception that stops the program unless handled. So "End of program" is not printed.
What will this C# program print?
using System; class Program { static void Main() { int[] numbers = {1, 2, 3}; try { Console.WriteLine(numbers[5]); } catch (IndexOutOfRangeException) { Console.WriteLine("Index error caught"); } Console.WriteLine("Program continues"); } }
What does the catch block do when an exception occurs?
The try block causes an exception, which is caught by the catch block that prints a message. Then the program continues.
What exception will this code throw when run?
using System; class Program { static void Main() { string text = null; Console.WriteLine(text.Length); } }
What happens if you try to access a property of a null object?
Accessing a member of a null object causes a NullReferenceException in C#.
Why is using exception handling preferred over returning error codes in C#?
Think about how code looks and behaves when errors are handled separately.
Exception handling lets programmers write normal code without cluttering it with error checks, improving readability and maintainability.