---
# System prepended metadata

title: 數值溢位
tags: [CSharp]

---

#    數值溢位
以下範例Add有隱含的錯誤，若num1 + num2超過 `int.MaxValue`則會報錯。
**The operation overflows at compile time in checked mode**

```csharp=
static void Main(string[] args)
{
	int num1 = 100, num2 = 20;
	int result = Add(num1, num2);

	Console.WriteLine(result);
}

static int Add(int num1, int num2)
{
	return num1 + num2;
}
```
正確作法有兩種。
1. 如遇到溢位則報出Exception(checked)
```csharp=
static void Main(string[] args)
{
	int num1 = 100, num2 = 20;
    try{
        int result = Add(num1, num2);
        
        Console.WriteLine(result);
    }catch(Exception ex){
        Console.WriteLine(ex.Message);
    }
	
}

static int Add(int num1, int num2)
{    
    checked{
	    return num1 + num2;
    }
}
```
2. 如遇到溢位不報錯依然執行(unchecked)
```csharp=
static void Main(string[] args)
{
	int num1 = int.MaxValue, num2 = 20;
    try{
        int result = Add(num1, num2);

        Console.WriteLine (result);
    }
    catch (Exception ex)
    {
        Console.WriteLine (ex.Message);
    }

}

static int Add (int num1, int num2)
{
    unchecked
    {
        return num1 + num2;
    }
}
```
###### tags: `CSharp`
參考資料：https://docs.microsoft.com/zh-tw/dotnet/csharp/language-reference/keywords/checked-and-unchecked