Home > Article > Backend Development > Checked vs. unchecked exceptions in C#
You can execute statements in C# in checked or unchecked context.
In a checked context, arithmetic overflows raise an exception, whereas in an unchecked context, arithmetic overflows are ignored.
Use the checked keyword to explicitly enable overflow checking for integer arithmetic operations and conversions. To do this, just set the checked keyword.
Overflow checking can be enabled through compiler options, environment configuration, or using the checked keyword.
res = checked(val + 10);
Assume that the value of val is 2147483647, which is the maximum value of the int type. Since it's checked, the above will throw an error. This enables overflow checking at runtime.
Use the unchecked keyword to prevent overflow checking for integer arithmetic operations and conversions. To do this, just set the unchecked keyword.
Here, arithmetic overflow is ignored. Use this to prevent overflow checking.
res =unchecked(val + 10);
Assume the value of val is 2147483647. The above code does not throw an error because overflow checking is prevented using the unchecked keyword.
The above is the detailed content of Checked vs. unchecked exceptions in C#. For more information, please follow other related articles on the PHP Chinese website!