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?
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);
}
...
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With