On 05/24/2014 10:09 AM, Tim wrote:

> I'm working on an application where I want log all exceptions but I'm
> not sure what's the best way to realize that.

A common solution is to log it in the exception class'es constructor. We even dump the backtrace with libunwind in our C++ application.

However, you may quickly realize that not every thrown exception is log-worthy. The reason is, e.g. a MyMissingFile exception may not be important when there is a default action to follow. No need to log in that case.

Just to note, although these are valid issues, exceptions are still the best option for error handling.

> Sure I can do the following:
>
> void myMethod() nothrow
> {
>     try
>     {
>       // Do something
>     }
>     catch (Exception e)
>     {
>       // Write log file
>     }
> }

As you say, that does not scale. :)

> 2) When I want create an application where all methods are defined
> as >nothrow< - how can I realize that? Writing to a log-file is already
> throwable.

You can bypass the compiler by wrapping the throwing expression in assumeWontThrow (as I have shown just yesterday during my DConf lightning talk. How timely... :))

Contrary to its name assumeWontThrow throws an Error (not Exception) if the expression actually throws.

// This function requires that the argument is less than 10
void bar(int i)
{
    import std.exception : enforce;

    enforce(i < 10);
    // ...
}

void foo() nothrow
{
    import std.exception : assumeWontThrow;

    // I know that bar(7) won't throw. So, it's
    // safe to bypass the compiler in this case.
    assumeWontThrow(bar(7));

    /* Note: UFCS may look less natural:
     *
     *     bar(7).assumeWontThrow;
     *
* bar(7) is NOT executed before assumeWontThrow. Rather, assumeWontThrow
     * takes a lazy parameter. So, bar(7) is assumed to be nothrow.
     */

    // ...
}

void main()
{
    foo();
}

Ali

Reply via email to