I can has @nogc and throw Exceptions?

Lodovico Giaretta via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Wed Jul 13 09:28:23 PDT 2016


On Wednesday, 13 July 2016 at 16:13:21 UTC, Adam Sansier wrote:
> On Wednesday, 13 July 2016 at 11:39:11 UTC, Lodovico Giaretta 
> wrote:
>> On Wednesday, 13 July 2016 at 00:57:38 UTC, Adam Sansier wrote:
>>> [...]
>>
>> You shall use a static per-thread Region allocator[1] backed 
>> by Mallocator[2].
>> Then you just make[3] exceptions inside it and throw them.
>> So you can allocate and chain exceptions until you end the 
>> memory established on creation.
>> Whenever you don't need the exception chain anymore (i.e.: you 
>> catched them and program is back in "normal" mode, you just 
>> reset the region allocator, so you have all of your memory 
>> again, for the next exception chain).
>>
>> [1] 
>> https://dlang.org/phobos/std_experimental_allocator_building_blocks_region.html
>> [2] 
>> https://dlang.org/phobos/std_experimental_allocator_mallocator.html
>> [3] https://dlang.org/phobos/std_experimental_allocator.html
>
> Am I going to have to do all this myself or is it already done 
> for me somewhere?

It's actually quite easy. Here's the code (untested):

================================================================

import std.experimental.allocator.building_blocks.region;
import std.experimental.allocator.mallocator;
import std.experimental.allocator;


Region(shared(Mallocator)) exception_allocator;
enum EXCEPTION_MEM_SIZE = 256*1024;
static this()
{
     exception_allocator = 
typeof(exception_allocator)(EXCEPTION_MEM_SIZE);
}

================================================================

And here is an usage example (untested, too):

================================================================

void throwingFunction()
{
     // try to do something, but fail
     throw exception_allocator.make!Exception("my wonderful error 
message");
}

void throwingThrowingFunction()
{
     try
     {
         // try to call function, which fails
         throwingFunction;
     }
     catch (Exception exc)
     {
         // try to recover from failure, but generate other 
exception (just to show chaining)
         throw exception_allocator.make!Exception("I love 
exception chaining");
     }
}

void main()
{
     try
     {
         // try to call function, which fails
         throwingThrowingFunction;
     }
     catch (Exception exc)
     {
         // recover from failure, then deallocate the exceptions 
no longer needed
         exception_allocator.deallocateAll;
     }
}
================================================================


More information about the Digitalmars-d-learn mailing list