The exception that is thrown when an arithmetic, casting, or conversion operation in a checked context results in an overflow.
See Also: OverflowException Members
An OverflowException is thrown at run time under the following conditions:
An arithmetic operation produces a result that is outside the range of the data type returned by the operation. The following example illustrates the OverflowException that is thrown by a multiplication operation that overflows the bounds of the int type.
code reference: System.OverflowException#1
A casting or conversion operation attempts to perform a narrowing conversion, and the value of the source data type is outside the range of the target data type. The following example illustrates the OverflowException that is thrown by the attempt to convert a large unsigned byte value to a signed byte value.
code reference: System.OverflowException#2
In each case, the result of the operation is a value that is less than the MinValue property or greater than the MaxValue property of the data type that results from the operation.
For the arithmetic, casting, or conversion operation to throw an OverflowException, the operation must occur in a checked context. By default, arithmetic operations and overflows in Visual Basic are checked; in C#, they are not. If the operation occurs in an unchecked context, the result is truncated by discarding any high-order bits that do not fit into the destination type. The following example illustrates such an unchecked conversion in C#. It repeats the previous example in an unchecked context.
code reference: System.OverflowException#3
The following Microsoft intermediate language (MSIL) instructions throw an OverflowException:
add.ovf.<signed>
conv.ovf.<to type>
conv.ovf.<to type>.un
mul.ovf.<type>
sub.ovf.<type>
newarr
OverflowException uses the HRESULT COR_E_OVERFLOW, which has the value 0x80131516.
For a list of initial property values for an instance of OverflowException, see the OverflowException.#ctor constructors.
The following example demonstrates an error that causes a OverflowException exception.
C# Example
using System; public class OverflowExample { public static void Main() { int i = 400; byte b = 0; try { checked { b = (byte)( i ); } } catch ( OverflowException e ) { Console.WriteLine( "Error caught: {0}", e ); } } }
The output is
Example
Error caught: System.OverflowException: Arithmetic operation resulted in an overflow. at OverflowExample.Main()