Ví dụ chia số, xử lý DivideByZeroException.
Ví dụ
using System;
namespace ErrorHandlingApplication
{
class DivNumbers
{
int result;
public void Division(int num1, int num2)
{
try
{
result = num1 / num2;
}
catch (DivideByZeroException e)
{
Console.WriteLine("Exception: {0}", e.Message);
}
finally
{
Console.WriteLine("Result: {0}", result);
}
}
static void Main(string[] args)
{
DivNumbers d = new DivNumbers();
d.Division(25, 0);
Console.ReadKey();
}
}
}
Kết quả
Exception: Attempted to divide by zero. Result: 0
Flow Control
- Exception trong try -> nhảy đến catch phù hợp
- Catch xong -> chạy finally
- Không exception -> try xong -> chạy finally
- Return trong try/catch -> finally vẫn chạy trước khi return
- Exception không catch -> finally chạy -> propagate lên caller
Best Practices
- Catch specific exception trước, general sau
- Không catch Exception chung trừ top-level
- Dùng
using/IDisposablecho resource cleanup (tự gọi Dispose trong finally) throw;preserve stack trace,throw ex;reset stack trace