Overflow Exception Handling Using Checked and Unchecked

overflow-exception
In this Section you will learn:

  • What is Checked and Unchecked
  • How to get correct result while using small size variable in arithmetic operation like byte, sbyte or short?
  • How to handle overflow exception with checked and unchecked statement?

As a C# programmer you always should be aware of correct output of arithmetic operation. Your code might be correct, there is no runtime exception still your output may be incorrect and it may cause serious problem in your project. To understand this theory, see this programming example first.

Programming Example

Output

20 x 30 = 88
__

 

  • Explanation

    In this example, we have used sbyte variable for simple arithmetic calculation. The multiply of num1 and num2 should be 600 but you will get output 88. It will not raise any exception and error still your program is incorrect. It is done because you have used very small variable without using checked andunchecked statement. The size of sbyte is -128 to 127 only; so the result is overflowed.

    How to handle overflow exception using checked and unchecked statement?

    It is very easy to fix this problem using checked and unchecked statement.Checked strictly monitor your code and if any overflow exception generated it sends control to catch for handling exception. Unchecked statement ignores overflow exception and shows output.

    To understand it, see the programming example of checked and unchecked statements.

    Programming Example

    Output

    20 x 30 = 88

    Arithmetic operation resulted in an overflow.
    __

     

    Explanation

    In this example, we have the same program as above but in the checked andunchecked block with exception handling. You will see two outputs; first one is unchecked output that is 88 and second one is overflow exception message.

    Note: Most of the beginners always make this mistake while creating project thus the project shows incorrect result. It is not harmful to use checked and unchecked statements everywhere so while doing project which is mostly based on arithmetic calculation you must be strict on overflow exception.

    Summary

    In this chapter you have learned how to handle overflow exception using checked and unchecked statement in c#. It is very important to be aware of incorrect output while using small size variables. In the next chapter you will understand exception handling more clearly with some programming examples.


    One thought on “Overflow Exception Handling Using Checked and Unchecked”

    Leave a Reply

    Your email address will not be published. Required fields are marked *