try-catch绕数字增量

时间:2016-11-03 08:55:19

标签: c# .net

我已经看过以下c#代码:

MyClass c = new MyClass();

try { 
   c.Counter++; 
} catch (Exception ex) {
   Console.WriteLine(ex.StackTrace); 
}

并且想知道,围绕数字增量的try{} catch(){}可能在.NET世界中起作用的目的是什么?

2 个答案:

答案 0 :(得分:4)

捕获整数溢出异常 OverflowException

  // integer overflow policy (what the system should do if integer value
  // is out of [int.MinValue..int.MaxValue] range - 
  // throw the OverflowException or just allow the overflow) 
  // is regulated either explictly
  // by checked/unchecked keywords 
  // or implictly by /checked compiler directive, project settings etc.
  checked { // switch integer overflow check on to ensure OverflowException be thrown
    ...

    MyClass c = new MyClass();

    c.Counter = int.MaxValue; // maximum possible value

    try { 
      c.Counter++; // let's try to add up 1 to maximum possible value
    } catch (Exception ex) {
      // ... And we'll have the exception thrown
      Console.WriteLine(ex.StackTrace); 
    }

    ...
  }

答案 1 :(得分:2)

Counter似乎是一个属性,所以在那里真的可以发生任何事情(甚至数据库访问,多线程访问共享资源等等)。当然,这样做并不是一个好主意,但从技术上讲,没有什么能阻止人们这样做。