การหารด้วยศูนย์ (Divide by Zero) ใน C#
พฤติกรรมขึ้นอยู่กับ **ชนิดข้อมูล** ของตัวเลข
Integer Types (int, long, byte, short, etc.) → Exception
using System;
class Demo
{
static void Main()
{
int a = 10;
int b = 0;
try
{
int result = a / b; // โยน DivideByZeroException
}
catch (DivideByZeroException ex)
{
Console.WriteLine($"Exception: {ex.Message}");
// "Attempted to divide by zero."
}
}
}
Floating-point Types (float, double) → Infinity/NaN
using System;
class Demo
{
static void Main()
{
double a = 10.0;
double b = 0.0;
double result = a / b; // ไม่โยน Exception!
Console.WriteLine($"Result: {result}"); // Infinity
Console.WriteLine($"IsInfinity: {double.IsInfinity(result)}"); // True
Console.WriteLine($"IsPositiveInfinity: {double.IsPositiveInfinity(result)}"); // True
// 0.0 / 0.0 = NaN
double nan = 0.0 / 0.0;
Console.WriteLine($"0/0 = {nan}"); // NaN
Console.WriteLine($"IsNaN: {double.IsNaN(nan)}"); // True
}
}
ผลลัพธ์
Result: ∞
IsInfinity: True
IsPositiveInfinity: True
0/0 = NaN
IsNaN: True
Decimal Type → Exception
decimal d = 10m / 0m; // โยน DivideByZeroException (เหมือน integer)
ตารางสรุปพฤติกรรม
| Type | x / 0 (x ≠ 0) | 0 / 0 | Exception? |
|---|---|---|---|
| int, long, short, byte, uint, ulong... | DivideByZeroException | DivideByZeroException | ✅ Yes |
| float, double | ±Infinity | NaN | ❌ No |
| decimal | DivideByZeroException | DivideByZeroException | ✅ Yes |
การจัดการข้อยกเว้น DivideByZeroException
public double SafeDivide(double dividend, double divisor)
{
if (divisor == 0)
{
// ตัดสินใจเอง: โยน exception, คืนค่า special, หรือ log
throw new DivideByZeroException("Cannot divide by zero");
// หรือ return double.NaN;
// หรือ return double.PositiveInfinity;
}
return dividend / divisor;
}
// สำหรับ integer - ต้อง try-catch
public int SafeDivideInt(int a, int b)
{
if (b == 0) throw new DivideByZeroException();
return a / b;
}
// หรือใช้ Try pattern
public bool TryDivide(int a, int b, out int result)
{
if (b == 0) { result = 0; return false; }
result = a / b;
return true;
}
ตรวจสอบ Infinity/NaN
double result = 1.0 / 0.0; // Infinity
if (double.IsInfinity(result))
Console.WriteLine("Infinity!");
if (double.IsNaN(result))
Console.WriteLine("NaN!");
// ตรวจสอบแบบรวม
if (!double.IsFinite(result)) // C# 9+ (.NET 5+)
Console.WriteLine("Not a finite number");
Best Practices
- ตรวจสอบก่อนหาร สำหรับ integer/decimal
- ใช้ double.IsNaN/IsInfinity สำหรับ floating-point
- หลีกเลี่ยงการเปรียบเทียบ NaN -
NaN != NaNเป็น true เสมอ ใช้double.IsNaN() - Unit Test** กรณี edge cases (0, -0, MinValue, MaxValue)
Math.DivRem - หารพร้อมเศษ
int dividend = 10, divisor = 3;
int quotient = Math.DivRem(dividend, divisor, out int remainder);
// quotient = 3, remainder = 1
// ต้องตรวจสอบ divisor != 0 เอง