1. 用 try{ } catch(OverflowException){ } 包起來, 運算式用 check/ uncheck包起來
checked ( 運算式 )/ unchecked ( 運算式 )
try
{
uint y = unchecked(x + 1); //unchecked: 不檢查
//uint y = checked(x + 1); //checked: 檢查 -> Overflow -> OverflowException
Console.WriteLine(y);
}
catch (OverflowException ex)
{
Console.WriteLine("There's overflow!");
}
2. 使用 checked { } / uncheck{ } 檢查是否異常
checked{ } (拋出溢出) / unchecked { } (不拋出溢出)
checked
{
try
{
uint y = x + 1;
Console.WriteLine(y);
}
catch (OverflowException ex)
{
Console.WriteLine("There's overflow!");
}
}
For test:
uint x = uint.MaxValue;
Console.WriteLine(x);
string binStr = Convert.ToString(x, 2); //result: 32位個1
Console.WriteLine(binStr);
//uint y = x + 1; //會溢出
//Console.WriteLine(y); //result = 0
沒有留言:
張貼留言