A. There is no error; code handles exception correctly
B. The finally block is missing
C. The catch block should catch NullReferenceException instead
D. The array size is too big
Solution
Step 1: Analyze the try block code
The code accesses index 5 of an array with size 3, causing an IndexOutOfRangeException.
Step 2: Check the catch and finally blocks
The catch block correctly catches IndexOutOfRangeException and prints a message. The finally block prints "Done." This is correct usage.
Final Answer:
There is no error; code handles exception correctly -> Option A
Quick Check:
Correct catch and finally usage = A [OK]
Hint: Catch correct exception type and use finally for cleanup [OK]
Common Mistakes:
Catching wrong exception type
Forgetting finally block
Assuming array size causes error
5. You want to read a number from user input and handle errors if the input is not a number. Which code snippet correctly uses exception handling to do this?
hard
A. try {
int num = int.Parse(Console.ReadLine());
Console.WriteLine($"You entered {num}");
} catch (FormatException) {
Console.WriteLine("Please enter a valid number.");
}
B. int num = int.Parse(Console.ReadLine());
Console.WriteLine($"You entered {num}");
C. try {
int num = Console.ReadLine();
Console.WriteLine($"You entered {num}");
} catch (Exception) {
Console.WriteLine("Error occurred.");
}
D. try {
int num = Convert.ToInt32(Console.ReadLine());
} finally {
Console.WriteLine("Input processed.");
}
Solution
Step 1: Understand the goal
We want to read a number and catch errors if input is not a valid number.
Step 2: Check each option for correct exception handling
try {
int num = int.Parse(Console.ReadLine());
Console.WriteLine($"You entered {num}");
} catch (FormatException) {
Console.WriteLine("Please enter a valid number.");
} uses try with int.Parse and catches FormatException, which is correct. int num = int.Parse(Console.ReadLine());
Console.WriteLine($"You entered {num}"); has no error handling. try {
int num = Console.ReadLine();
Console.WriteLine($"You entered {num}");
} catch (Exception) {
Console.WriteLine("Error occurred.");
} tries to assign string to int without parsing. try {
int num = Convert.ToInt32(Console.ReadLine());
} finally {
Console.WriteLine("Input processed.");
} uses finally but no catch, so errors are not handled.
Final Answer:
try {
int num = int.Parse(Console.ReadLine());
Console.WriteLine($"You entered {num}");
} catch (FormatException) {
Console.WriteLine("Please enter a valid number.");
} -> Option A
Quick Check:
Try-catch with int.Parse and FormatException = A [OK]
Hint: Use try-catch around int.Parse to catch invalid input [OK]