Difference between revisions of "Exception re-throwing helper"

From D Wiki
Jump to: navigation, search
(initial)
 
(syntaxhighlight)
 
(4 intermediate revisions by one other user not shown)
Line 1: Line 1:
[[Category: Meta Programming]]
 
 
{{Cookbook
 
{{Cookbook
 +
|category=Meta Programming
 
|level=Novice
 
|level=Novice
 
|type=Recipe
 
|type=Recipe
Line 9: Line 9:
 
}}
 
}}
 
This recipe shows a helper function to handle the following scenario:
 
This recipe shows a helper function to handle the following scenario:
<pre>
+
 
 +
<syntaxhighlight lang="D">
 
try
 
try
 
{
 
{
Line 18: Line 19:
 
     throw new SomeOtherException("Caught Exception: SomeException:\n" ~ e.toString() );
 
     throw new SomeOtherException("Caught Exception: SomeException:\n" ~ e.toString() );
 
}
 
}
</pre>
+
</syntaxhighlight>
  
 
The program code is given in the next section.
 
The program code is given in the next section.

Latest revision as of 03:26, 18 February 2018

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)) );
}