checked 溢出问题

csharp 复制代码
 {
     try
     {
         int i = int.MaxValue;
         int j;
         checked
         {
             j = i + 1;
         }
        
     }
     catch (OverflowException er)
     {

         Console.WriteLine($"加Checked------>{er.Message}");
     }
     
 }
 {
     try
     {
         int i = int.MaxValue;
         int j;
         j = i + 1;
     }
     catch (OverflowException  er)
     {

         Console.WriteLine($"没有加Checked------>{er.Message}");
     }
     

    
 }
  • 溢出检查 :在 checked 关键字包围的代码块中,如果发生整数溢出,编译器会抛出 OverflowException 异常。

  • 默认行为:在 C# 中,默认情况下,整数运算不会检查溢出,如果发生溢出,结果会被截断,而不是抛出异常。

所以即使发生溢出,也不会抛出异常。结果是 i + 1 被截断为 int 类型的最小值,因为整数溢出是环绕 的。

相关推荐
知本知至1 个月前
kubuntu24.04配置vmware17.5.1
ubuntu·typora·vmware·net·kubuntu
Ares-Wang1 个月前
Visual Studio 同一解决方案 同时运行 多个项目
net
CheungChunChiu2 个月前
Android10 rk3399 以太网接入流程分析
android·framework·以太网·eth·net·netd
秋雨雁南飞3 个月前
net 站点安全 OwaspHeaders.Core
安全·net
Ares-Wang3 个月前
core 不可变类型 线程安全 record
net
子不语6 个月前
c#实现数据导出为PDF的方式
pdf·c#·导出·文档·net
Ares-Wang7 个月前
句 柄 概 念
net
Ares-Wang7 个月前
NET 定时器 Timer和线程Thread
net
Ares-Wang7 个月前
NET 语言识别,语音控制操作、语音播报
net