Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

try-catch around numeric increment

Tags:

c#

.net

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?

like image 785
user66875 Avatar asked Feb 16 '26 15:02

user66875


2 Answers

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 - 
  // 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); 
    }

    ...
  }
like image 152
Dmitry Bychenko Avatar answered Feb 19 '26 05:02

Dmitry Bychenko


Counter seems to be a property, so anything really can happen inside there (even DB access, access to a shared resource by multiple threads and so on). It won't be a good idea to do that of course, but technically nothing prevents one from doing so.

like image 31
Ilya Chernomordik Avatar answered Feb 19 '26 05:02

Ilya Chernomordik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!