Yan Cui
I help clients go faster for less using serverless technologies.
This article is brought to you by
Don’t reinvent the patterns. Catalyst gives you consistent APIs for messaging, data, and workflow with key microservice patterns like circuit-breakers and retries for free.
C#
By default, arithmetic operations and conversions in C# execute in an unchecked context, you can use the checked keyword to switch a block of code to the checked context so that any arithmetic overflow that occurs in that block of code will cause the OverflowException to be thrown:
However, the scope of the checked context is local to the method – i.e. if in your checked block you call another method then that method is not part of your scope and can cause arithmetic overflow without throwing any exceptions:
This might seem strange at first, but the reason for it is that whether or not an exception should be thrown for an arithmetic overflow/underflow is baked into the MSIL code the compiler generates rather than a runtime decision. When the OverflowInt method above is compiled, it’s compiled to NOT throw any exceptions when an overflow occurs, therefore regardless of where the method is called from no OverflowException will be thrown from inside the OverflowInt method.
However, it is possible to change the default behaviour for a given project by making a simple change to a project setting. Right-click on a project (inside VS) and go into project properties, find the Build tab, and click “Advanced…”. In the subsequent pop-up dialog there’s a ‘Check for arithmetic overflow/underflow’ checkbox:
F#
F# uses a different approach, it uses operator shadowing so that whenever you open the Checked module it overloads the standard arithmetic operators to include checks for arithmetic overflow/underflow and throws the OverflowException:
Suppose if you have the following module, the function f will not throw exceptions for arithmetic overflows because at the point it is defined the arithmetic operators have not been overloaded yet:
Subsequently, if you have code that uses this module, the overloaded operators from the Checked module will not apply here just because you’ve opened an module that imports the Checked module:
It is possible to simulate the behaviour of the C# checked keyword as Tomas Patricek suggested here, although his solution only works for the int type but nonetheless it gives you a good idea of how one might be able to do so:
Whenever you’re ready, here are 3 ways I can help you:
- Production-Ready Serverless: Join 20+ AWS Heroes & Community Builders and 1000+ other students in levelling up your serverless game. This is your one-stop shop for quickly levelling up your serverless skills.
- I help clients launch product ideas, improve their development processes and upskill their teams. If you’d like to work together, then let’s get in touch.
- Join my community on Discord, ask questions, and join the discussion on all things AWS and Serverless.