- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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.