Exercises in this lecture   Go to the notes, in which this exercise belongs -- Keyboard shortcut: 'u'   Alphabetic index   Course home   

Exercise solution:
Exceptions in Convert.ToDouble


If you consult the documentation of the method ToDouble in class System.Format you will find out that ToDouble may throw a FormatException or an OverflowException.

The following program demonstrates the throwing and pseudo-handling of the exceptions FormatExceptions and OverflowException, as triggered by using System.Format.ToDouble on strings.

using System;

class Program{

  public static void Main(){
 
     double d = 1,
            e = 2,
            f = 3;

     try{
       e = Convert.ToDouble("123.45-6");
     }
     catch (FormatException){
        Console.WriteLine("We got a FormatException");
        throw;                                        // rethrowing
     }
     catch (OverflowException){
        Console.WriteLine("We got an OverflowException");
        throw;                                        // rethrowing
     }
     catch (Exception){
        Console.WriteLine("We got another Exception");
        throw;                                        // rethrowing
     }

     try{
       f = Convert.ToDouble("12355555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555");
       }
     catch (FormatException){
        Console.WriteLine("We got a FormatException");
        throw;                                        // rethrowing
     }
     catch (OverflowException){
        Console.WriteLine("We got an OverflowException");
        throw;                                        // rethrowing
     }
     catch (Exception){
        Console.WriteLine("We got another Exception");
        throw;                                        // rethrowing
     }

     Console.WriteLine("{0} {1} {2}", d, e, f);

  }

}

In order to provoke an OverflowException you must type very many ciffers before the decimal point (more than 300). You can also provide a string such as "1,8E308". Recall that the the minimum and maximum doubles are -1,79769313486232E+308 and 1,79769313486232E+308 respectively.

Due to the rethrowing, the output of the program only reveals the FormatException. The reason is that FormatException will lead to a program halt, and therefore we never come to the conversion of the long string with lots of fives. If you - against all recommendations - eliminate the rethrowing you can observe the OverflowException as well.