Xử lý ngoại lệ là một phần quan trọng trong việc phát triển ứng dụng C#. Ngoại lệ xảy ra khi có lỗi xảy ra trong thời gian chạy chương trình. Điều này yêu cầu việc xử lý ngoại lệ để chương trình không bị đình chỉ và cung cấp thông báo lỗi rõ ràng cho người dùng.
Tất cả các ngoại lệ đều kế thừa từ lớp Exception. Đây là một điểm quan trọng trong cấu trúc xử lý ngoại lệ của C#.
using System;
using System.Collections.Generic;
namespace CSharpExamples
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Nhập một số:");
try
{
int value = int.Parse(Console.ReadLine());
}
catch (FormatException fe)
{
Console.WriteLine("Lỗi định dạng: " + fe.Message);
}
catch (Exception ex)
{
Console.WriteLine("Lỗi không mong đợi: " + ex.Message);
}
finally
{
Console.WriteLine("Bлок finally luôn được thực thi.");
}
}
}
}
Khi chạy đoạn mã trên và nhập một giá trị không phải số, chương trình sẽ hiển thị thông báo lỗi tương ứng.Tạo một lớp ngoại lệ tùy chỉnh:
using System;
namespace CSharpExamples
{
public class CustomOperationException : Exception
{
private DateTime timestamp;
public DateTime Timestamp
{
get { return timestamp; }
set { timestamp = value; }
}
private string errorId;
public string ErrorId
{
get { return errorId; }
set { errorId = value; }
}
public CustomOperationException(string id, Exception innerException) : base(innerException.Message)
{
errorId = id;
timestamp = DateTime.Now;
}
public void DisplayErrorDetails()
{
Console.WriteLine("Thời gian xảy ra lỗi: " + this.Timestamp);
Console.WriteLine("Mã lỗi: " + this.ErrorId);
Console.WriteLine("Thông báo lỗi: " + this.Message);
}
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Nhập một số:");
try
{
int value = int.Parse(Console.ReadLine());
}
catch (FormatException fe)
{
CustomOperationException myException = new CustomOperationException("E001", fe);
myException.DisplayErrorDetails();
}
catch (Exception ex)
{
Console.WriteLine("Lỗi không mong đợi: " + ex.Message);
}
Console.ReadKey();
}
}
}
Kết quả khi chạy:
Nếu người dùng nhập một giá trị không phải số, chương trình sẽ hiển thị thông báo lỗi định dạng. Nếu xảy ra lỗi khác, thông báo lỗi không mong đợi sẽ được hiển thị.