แบบฝึกหัด - ทํากิจกรรมการทดสอบให้เสร็จสมบูรณ์เพื่อจับข้อยกเว้นที่เฉพาะเจาะจง
ความท้าทายของโค้ดในโมดูลนี้ใช้เพื่อเสริมกําลังสิ่งที่คุณได้เรียนรู้และช่วยให้คุณได้รับความเชื่อมั่นก่อนที่จะดําเนินการต่อ
การทดสอบข้อยกเว้นที่จับได้
ในการทดสอบนี้ คุณจะได้ตัวอย่างรหัสที่สร้างข้อยกเว้นหลายประเภท บล็อกรหัสเดียว 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.
โชคดี!