user66875 user66875 - 1 month ago 14
C# Question

try-catch around numeric increment

I've seen the following c# code:

MyClass c = new MyClass();

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


and was wondering, what purpose a
try{} catch(){}
around a numeric increment could possibly serve in the .NET world?

Answer

To catch integer overflow exception OverflowException:

  // integer overflow policy (what the system should do if integer value
  // is out of [int.MinValue..int.MaxValue] range) 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); 
    }

    ...
  }