TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

C# OverflowException

This C# page describes the OverflowException. This exception is thrown in a checked context.

OverflowException. What could provoke an OverflowException?

An OverflowException is only thrown in a checked context. It alerts you to an integer overflow: a situation where the number becomes too large to be represented in the bytes.

Example. Let's look at this simple program. It declares a checked programming context inside the Main method. Next, we assign an int variable to one greater than the maximum value that can be stored in an int.

Intint.MaxValue

Note: An int is four bytes. More bytes would be needed to represent the desired number.

C# program that causes OverflowException

class Program
{
    static void Main()
    {
	checked
	{
	    int value = int.MaxValue + int.Parse("1");
	}
    }
}

Output

Unhandled Exception: System.OverflowException: Arithmetic operation resulted in
an overflow.

We end up with an OverflowException. This could be trapped in a catch block if you needed to handle the problem at runtime. Using a checked context can help alert you to logic problems in your program faster.

Discussion. With the checked context, bugs in our programs that would be silently ignored are changed into serious errors. Control flow is interrupted and programs are terminated. These bugs do not silently slip into the program.

In the above program, if you use no checked context (or the unchecked context), the program proceeds like nothing is amiss. It doesn't give you the number you probably expect. And this could cause problems you don't expect.

CheckedUnchecked

Summary. The OverflowException is a useful way of learning of logical errors in our C# programs. With the checked context, we detect these hard-to-find bugs. We improve the logic of our software in a more systematic way.


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf