Complete the code to catch a general exception.
try { int result = 10 / 0; } catch ([1] e) { Console.WriteLine("Error occurred"); }
The Exception type is used to catch general exceptions in C#.
Complete the code to catch a specific exception type for division by zero.
try { int result = 10 / 0; } catch ([1] e) { Console.WriteLine("Cannot divide by zero."); }
The DivideByZeroException is thrown when division by zero occurs.
Fix the error in the catch block to catch multiple exceptions separately.
try { string text = null; Console.WriteLine(text.Length); } catch ([1] e) { Console.WriteLine("Null reference error."); } catch (Exception e) { Console.WriteLine("General error."); }
The NullReferenceException is used to catch errors when accessing members of a null object.
Fill both blanks to catch specific exceptions and a general exception.
try { int[] numbers = {1, 2, 3}; Console.WriteLine(numbers[5]); } catch ([1] e) { Console.WriteLine("Index error."); } catch ([2] e) { Console.WriteLine("Other error."); }
The IndexOutOfRangeException catches errors when accessing invalid array indexes, and Exception catches all other errors.
Fill all three blanks to catch multiple exceptions and print their messages.
try { string input = null; int length = input.Length; int result = 10 / 0; } catch ([1] e) { Console.WriteLine("Null error: " + e.Message); } catch ([2] e) { Console.WriteLine("Divide error: " + e.Message); } catch ([3] e) { Console.WriteLine("General error: " + e.Message); }
Catch NullReferenceException first, then DivideByZeroException, and finally the general Exception.