Checked statement in c#

In this article we will learn about Checked statement in C#.
  • 3213

Introduction

The checked statement is an Exception statement. Checked statement is used to control an exception, this exception is raised whenever stack overflow (or underflow) occurs due to type conversion issues. It can be used as an operator or a statement according to the following forms.

The checked statement:

checked block

Example

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

namespace Checked_Statements

{

    class Program

    {

        static void Main(string[] args)

        {

            int num;

            // assign maximum value

            num = int.MaxValue;

            try

            {

                checked

                {

                    // forces stack overflow exception

                    num = num + 1;

                    Console.WriteLine(num);

                }

            }

            catch (Exception e)

            {

                Console.WriteLine(e.ToString());

            }

            Console.ReadLine();

        }

    }

}

 

The output of following program


Clipboard182.jpg

© 2020 DotNetHeaven. All rights reserved.