Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Khối finally trong C# là gì?

Khối finally dùng để thực thi một tập câu lệnh,无论 có exception được ném hay không. Ví dụ: mở file thì phải đóng dù có exception hay không.

Các khối xử lý lỗi triển khai bằng từ khóa try, catch, finally.

Ví dụ

Thử chạy code sau để triển khai finally:

using System; 
namespace ErrorHandlingApplication { 
    class DivNumbers { 
        int result; 
        DivNumbers() { 
            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); 
            } 
        } 
        static void Main(string[] args) { 
            DivNumbers d = new DivNumbers(); 
            d.division(25, 0); 
            Console.ReadKey(); 
        } 
    } 
}