checked
operator checks the runtime overflow.
The checked
operator tells the runtime to generate an OverflowException
.
using System;
class Program
{
static void Main(string[] args)
{
int i = int.MinValue;
int result = checked(i - 1);
Console.WriteLine("i=" + i);
Console.WriteLine("result="+result);
Console.WriteLine("result is int.MaxValue:" + (result == int.MaxValue));
}
}
The output:
Unhandled Exception: System.OverflowException: Arithmetic operation resulted in
an overflow.
at Program.Main(String[] args)
Other than expression checking shown in the code above, checked operator can also check a block of code.
using System;
class Program
{
static void Main(string[] args)
{
int i = int.MinValue;
checked {
int result = i - 1;
Console.WriteLine("i=" + i);
Console.WriteLine("result=" + result);
Console.WriteLine("result is int.MaxValue:" + (result == int.MaxValue));
}
}
}
The output:
Unhandled Exception: System.OverflowException: Arithmetic operation resulted in
an overflow.
at Program.Main(String[] args)
java2s.com | Contact Us | Privacy Policy |
Copyright 2009 - 12 Demo Source and Support. All rights reserved. |
All other trademarks are property of their respective owners. |