Checked vs Unchecked Exceptions in C#


You can execute statements in C# in checked or unchecked context.

In checked, the exception is raised by arithmetic overflow, whereas in unchecked context, arithmetic overflow is ignored.

Checked Exceptions

Use the checked keyword to explicitly enable overflow checking for integral-type arithmetic operations and conversions. For this, just set the checked keyword.

Overflow checking can be enabled by compiler options, environment configuration, or use of the checked keyword.

res = checked(val + 10);

Let’s say the value of val is 2147483647 i.e. the max value of int type. The above will raise an error since it is checked. This enables overflow checking at runtime.

Unchecked Exception

Use the unchecked keyword to prevent overflow checking for integral-type arithmetic operations and conversions. For this, just set the unchecked keyword.

Here, the arithmetic overflow is ignored. Use it to prevent overflow checking.

res =unchecked(val + 10);

Let’s say the value of val is 2147483647. The above will not throw an error since the overflow checking is prevented using the unchecked keyword.

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 22-Jun-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements