# Checked vs Unchecked Exceptions in C#

CsharpProgrammingServer Side Programming

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.

Published on 20-Aug-2018 09:07:20