Bỏ qua để đến nội dung

Exception Handling

Exception là lỗi xảy ra khi chương trình đang chạy. Bắt lỗi ở nơi có thể xử lý được, không nuốt lỗi im lặng.

try
{
int number = int.Parse("abc");
}
catch (FormatException ex)
{
Console.WriteLine($"Sai định dạng: {ex.Message}");
}
finally
{
Console.WriteLine("Luôn chạy");
}
void Withdraw(decimal amount)
{
if (amount <= 0)
{
throw new ArgumentException("Amount must be positive");
}
}
class NotEnoughBalanceException : Exception
{
public NotEnoughBalanceException(string message) : base(message)
{
}
}
throw new NotEnoughBalanceException("Số dư không đủ");
Cú phápÝ nghĩa
tryKhối code có thể lỗi
catchBắt và xử lý lỗi
finallyLuôn chạy sau try/catch
throwNém lỗi
ExceptionLớp gốc của exception
try
{
await CallApiAsync();
}
catch (HttpRequestException ex) when (ex.StatusCode == HttpStatusCode.NotFound)
{
Console.WriteLine("Không tìm thấy tài nguyên");
}
catch (Exception ex)
{
Log(ex);
throw; // giữ stack trace gốc
}
ExceptionThường gặp khi
ArgumentExceptionArgument không hợp lệ
ArgumentNullExceptionArgument null không được phép
InvalidOperationExceptionObject đang ở trạng thái không thể xử lý
FormatExceptionParse sai định dạng
IndexOutOfRangeExceptionIndex ngoài phạm vi array
KeyNotFoundExceptionKey không có trong Dictionary
TaskCanceledExceptionAsync task bị hủy/timeout

Khi lỗi là tình huống bình thường, dùng Try... thay vì exception.

if (int.TryParse(input, out int age))
{
Console.WriteLine(age);
}
  • catch (Exception) quá rộng rồi không log gì.
  • Dùng exception cho luồng logic bình thường.
  • throw ex; làm mất stack trace; dùng throw;.
  • Nuốt lỗi bằng catch { }.
  • Bắt exception quá xa nơi có thể xử lý.
  • Hiển thị trực tiếp stack trace cho user cuối.

exception, xử lý lỗi, try, catch, finally, throw, throw ex, catch filter, custom exception, FormatException, ArgumentException, InvalidOperationException, TryParse