Checking for overflows.
using System;
public class MainClass {
public int CheckedAddition(short s1, short s2) {
int z = 0;
try {
z = checked((short)(s1 + s2));
} catch (OverflowException) {
Console.WriteLine("Overflow Exception, Returning 0");
}
return z;
}
public int UncheckedAddition(short s1, short s2) {
int z = ((short)(s1 + s2));
return z;
}
public static void Main() {
MainClass app = new MainClass();
short s1 = 32767;
short s2 = 32767;
Console.WriteLine("Checked Addition is: {0}",app.CheckedAddition(s1, s2));
Console.WriteLine("Unchecked Addition is: {0}",app.UncheckedAddition(s1, s2));
}
}
Related examples in the same category