คีย์เวิร์ดสุดท้ายถูกใช้เป็นบล็อกเพื่อดำเนินการชุดคำสั่งที่กำหนด ไม่ว่าจะส่งข้อยกเว้นหรือไม่ส่ง ตัวอย่างเช่น หากคุณเปิดไฟล์ จะต้องปิดไฟล์ไม่ว่าจะมีข้อยกเว้นหรือไม่
ไวยากรณ์
ต่อไปนี้เป็นไวยากรณ์ -
try {
// statements causing exception
} catch( ExceptionName e1 ) {
// error handling code
} catch( ExceptionName e2 ) {
// error handling code
} catch( ExceptionName eN ) {
// error handling code
} finally {
// statements to be executed
} ตัวอย่าง
ให้เรามาดูตัวอย่างการใช้งานบล็อกสุดท้าย -
using System;
public class Demo {
int result;
Demo() {
result = 0;
}
public void division(int num1, int num2) {
try {
result = num1 / num2;
} catch (DivideByZeroException e) {
Console.WriteLine("Exception caught = {0}", e);
} finally {
Console.WriteLine("Result = {0}", result);
}
}
public static void Main(string[] args) {
Demo d = new Demo();
d.division(100, 0);
}
} ผลลัพธ์
สิ่งนี้จะสร้างผลลัพธ์ต่อไปนี้ -
Exception caught = System.DivideByZeroException: Attempted to divide by zero. at Demo.division(Int32 num1, Int32 num2) in d:\Windows\Temp\n0kebv45.0.cs:line 11 Result = 0