This code is simply throw exception, because short sNum is assigned big range value of int num, and conversion fail. Any way.
I want to loop request until valid rang of short is entered.
static void Main()
{
int num = 40000;
short sNum = 0;
try
{
sNum = Convert.ToInt16(num);
}
catch (OverflowException ex)
{
// Request for input until no exception thrown.
Console.WriteLine(ex.Message);
sNum = Convert.ToInt16(Console.ReadLine());
}
Console.WriteLine("output is {0}",sNum);
Console.ReadLine();
}
Thank you.
The reason is you are throwing an exception when the conversion fails inside your
catchblock. Thecatchblock technically is outside of thetryblock, so it will not get caught by the samecatchas you seem to think. This is not really behaving as a loop as you appear to hope it will.Exceptions are not generally considered the best method for normal (non-exceptional) events in your code. The
TryParsemethod and a loop would be much better in this case.