short shortNumber = 32767; Console.WriteLine($"Org short number: {shortNumber}"); shortNumber += 1; Console.WriteLine($"Plus 1 to short number:{shortNumber}");
顯示結果如下:
1 2
Org short number: 32767 Plus 1 to short number:-32768
Console.WriteLine($"Plus 1 to short number:{checked(shortNumber+=1)}");
結果是直接跳出exception並告知以下結果:
1
Unhandled Exception: System.OverflowException: Arithmetic operation resulted in an overflow.
當然我們也可以預先使用try catch來攔截相關的錯誤
1 2 3 4 5 6 7 8 9 10 11
short shortNumber = 32767; Console.WriteLine($"Org short number: {shortNumber}"); try { Console.WriteLine($"Plus 1 to short number:{checked(shortNumber += 1)}"); } catch (System.OverflowException e) { Console.WriteLine($"Found overflow exception. Msg:\n{e}"); } Console.WriteLine($"Done");
結果就是毫無懸念的
1 2 3 4 5
Org short number: 32767 Found overflow exception. Msg: System.OverflowException: Arithmetic operation resulted in an overflow. at ConsoleAll.Program.Main(String[] args) in /Users/mingyi/Documents/vscode/Practice/ConsoleAll/ConsoleAll/Program.cs:line 13 Done