Home  >  Article  >  Backend Development  >  Checked vs. unchecked exceptions in C#

Checked vs. unchecked exceptions in C#

王林
王林forward
2023-08-27 14:13:14641browse

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.

Checked exceptions

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.

Unchecked Exception

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!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete