Adding more information to exceptions

Vladimir Panteleev vladimir at thecybershadow.net
Tue Jan 29 12:32:09 PST 2013


Let's say I have some code that parses some text file:

int[] numbers;
foreach (lineNumber, line; lines)
    numbers ~= to!int(line);

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.

Previously, I "solved" this like this:

foreach (lineNumber, line; lines)
    try
       numbers ~= to!int(line);
    catch (Exception e)
       throw new Exception(format("Error on line %d: %s", 
lineNumber, e.msg));

Of course, this has the problem that all information (except the 
message) from the original exception is lost.

I started using the following instead, which worked:

foreach (lineNumber, line; lines)
    try
       numbers ~= to!int(line);
    catch (Exception e)
       throw new Exception(format("Error on line %d", lineNumber), 
e);

This worked, however today I noticed in the documentation that 
the "next" parameter is reserved for exception chaining, and 
should not be used by user code.

So, I tried to do it the exception chaining way:

foreach (lineNumber, line; lines)
{
    scope(failure) throw new Exception(format("Error on line %d", 
lineNumber));
    numbers ~= to!int(line);
}

The above doesn't work - only the exception in scope(failure) is 
caught. Same if I try to throw from a catch block, but 
interestingly works if throwing from a finally block.

Q1: Is this a bug, or I just don't understand how exception 
chaining works?
Q2: Is there a better way to achieve this (adding information to 
in-flight exceptions)?


More information about the Digitalmars-d-learn mailing list