Adding more information to exceptions

Ali Çehreli acehreli at yahoo.com
Tue Jan 29 13:53:45 PST 2013


On 01/29/2013 12:32 PM, Vladimir Panteleev wrote:

 > I would like to add some information to any exceptions thrown inside the
 > loop's body (e.g. whatever std.conv.to may throw), in our case the line
 > number.

Here is a RAII idea that takes advantage of exception chaining without 
directly using the 'next' parameter. It constructs a LineInfo object 
ready to throw in its destructor unless specifically told that it is not 
necessary anymore.

import std.stdio;
import std.string;
import std.conv;

void main()
{
     auto lines = [ "42", "100", "hello" ];

     int[] numbers;

     struct LineInfo
     {
         size_t lineNumber;
         bool allIsGood = false;

         ~this()
         {
             if (!allIsGood) {
                 throw new Exception(format("Line number: %s", lineNumber));
             }
         }
     }

     foreach (lineNumber, line; lines) {
         auto info = LineInfo(lineNumber);
         numbers ~= to!int(line);
         info.allIsGood = true;
     }
}

Ali



More information about the Digitalmars-d-learn mailing list