Difference between revisions of "Exception re-throwing helper"

From D Wiki
Jump to: navigation, search
m (fix cat)
m
Line 96: Line 96:
  
 
</syntaxhighlight>
 
</syntaxhighlight>
 +
 +
__SHOWFACTBOX__

Revision as of 05:55, 16 December 2012

Level: Novice
Cookbook Type: Recipe
Cookbook Status: Draft
Approximate reading time: 10 min
0.166 hr
D Version: D2

This recipe shows a helper function to handle the following scenario:

try
{
    some_function();
}
catch(SomeException e)
{
    throw new SomeOtherException("Caught Exception: SomeException:\n" ~ e.toString() );
}

The program code is given in the next section.

Program Code

import std.exception;
import std.array;

template try_template(alias FE, alias TE)
{
   auto ref _try(T)(lazy T expression)
   {
        try
        {
            static if(!is(T==void))
            {   return ( expression() );
            }
            else
            {    expression();
            }
        }
        catch(FE fe)
        {
            throw new TE("Converting caught exception: " ~  FE.stringof ~ "\n\t> " ~ fe.toString().replace("\n", "\n\t> "));
        }
   }
}

mixin template try_convert(alias FE, alias TE, string name)
{
    mixin(`alias try_template!(` ~ FE.stringof ~ `,` ~ TE.stringof~ `)._try ` ~ name ~ `;`);
}

//////////////////////////////////////////////////////////////////////////////////////////////////

class FromEx: Exception
{
    this(string msg, string f = __FILE__, size_t l = __LINE__)
    {
        super(msg, f, l);
    }
}

class ToEx: Exception
{
    this(string msg, string f = __FILE__, size_t l = __LINE__)
    {
        super(msg, f, l);
    }
}

mixin try_convert!(FromEx, ToEx, "tryFT");

void from()
{
    throw new FromEx("haha");
}

int from2(int x)
{
    if(x == 0)
        throw new FromEx("haha2");

    return 123;
}

void main()
{
    assertThrown!(ToEx)( tryFT(from()) );
    assertThrown!(ToEx)( tryFT(from2(0)) );

    assertNotThrown( tryFT(from2(999)) );
    assert( 123 == tryFT(from2(999)) );
}