练习 - 完成捕获特定异常的挑战活动
本模块中的代码挑战可以巩固你学到的知识,帮助你在继续操作之前增强自信。
捕获特定异常挑战
在此挑战中,为你提供了一个代码示例,该代码示例可生成多个不同的异常类型。 单个 try
代码块包含生成异常的代码。 包含多个 catch
子句来处理特定的异常类型。
你需要更新代码示例,以便捕获每个异常,并在控制台中显示相应的错误消息。
下面是此挑战的要求:
确保 Program.cs 文件包含以下代码示例:
try { int num1 = int.MaxValue; int num2 = int.MaxValue; int result = num1 + num2; Console.WriteLine("Result: " + result); string str = null; int length = str.Length; Console.WriteLine("String Length: " + length); int[] numbers = new int[5]; numbers[5] = 10; Console.WriteLine("Number at index 5: " + numbers[5]); int num3 = 10; int num4 = 0; int result2 = num3 / num4; Console.WriteLine("Result: " + result2); } catch (OverflowException ex) { Console.WriteLine("Error: The number is too large to be represented as an integer." + ex.Message); } catch (NullReferenceException ex) { Console.WriteLine("Error: The reference is null." + ex.Message); } catch (IndexOutOfRangeException ex) { Console.WriteLine("Error: Index out of range." + ex.Message); } catch (DivideByZeroException ex) { Console.WriteLine("Error: Cannot divide by zero." + ex.Message); } Console.WriteLine("Exiting program.");
更新代码,以便在发生异常类型时在控制台中显示每个错误消息。
验证更新的代码是否将以下消息打印到控制台:
Error: The number is too large to be represented as an integer. Arithmetic operation resulted in an overflow. Error: The reference is null. Object reference not set to an instance of an object. Error: Index out of range. Index was outside the bounds of the array. Error: Cannot divide by zero. Attempted to divide by zero. Exiting program.
祝你好运!