Checked vs. unchecked exceptions in C#

王林
Release: 2023-08-27 14:13:14
forward
675 people have browsed it

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);
Copy after login

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);
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!