How to catch overflow exception in C#

1 Answer

0 votes
using System;

public class Overflow
{
    public static void Main(string[] args)
    {
        int x = int.MaxValue;
        try
        {
            checked // "Checked" is a block keyword that enables arithmetic overflow checking. 
            {
                int result = x + 1;
                Console.WriteLine("No Overflow!");
            }
        }
        catch (OverflowException ex)
        {
            Console.WriteLine("Overflow Exception caught: " + ex.Message);
        }
    }
}


/*
run:

Overflow Exception caught: Arithmetic operation resulted in an overflow.

*/

 



answered May 18, 2025 by avibootz

Related questions

1 answer 132 views
1 answer 139 views
1 answer 167 views
1 answer 158 views
1 answer 201 views
...