try/catch idiom in std.datetime

Shammah Chancellor anonymous at coward.com
Thu Nov 21 18:35:39 PST 2013


On 2013-11-22 02:07:36 +0000, growler said:

> On Friday, 22 November 2013 at 01:49:11 UTC, Shammah Chancellor wrote:
>> On 2013-11-18 06:32:46 +0000, Andrei Alexandrescu said:
>>> 
>>> 1. Fix scope(failure) and then use it.
>>> 
>>> Andrei
>> 
>> Huh?  Scope failure has no purpose here.  It does not CATCH the 
>> exception and prevent it from bubbling up the call chain.    Try/catch 
>> does do this.
>> 
>> -Shammah
> 
> It does if you return from the scope(failure) block. The problem is you 
> cannot mark the function as "nothrow"
> 
> For example:
> ---
> void throwingFunction() {
>      throw new Exception("damn!");
> }
> 
> void someFunc() // nothrow
> {
>      scope(failure) {
>          writeln("Failed in someFunc()");
>          return;
>      }
>      throwingFunction();
> }
> 
> void main() {
>      try {
>          someFunc();
>          writeln("Yay, someFunc() is nothrow");
>      } catch(Exception e) {
>          writeln("An exception in main!");
>      }
> }
> 
> Output:
> 
> Failed in someFunc()
> Yay, someFunc() is nothrow.
> ---
> 
> But you cannot mark someFunc() as nothrow.

What!?  That shouldn't even be legal code!   See below for why:

void throwingFunction() {
     throw new Exception("damn!");
}

void someFunc() // nothrow
{
    scope(failure) { writeln("What?");} <-- NEVER EXECUTED?!
     scope(failure) {
         writeln("Failed in someFunc()");
         return;
     }
     throwingFunction();
}

void main() {
     try {
         someFunc();
         writeln("Yay, someFunc() is nothrow");
     } catch(Exception e) {
         writeln("An exception in main!");
     }
}



More information about the Digitalmars-d mailing list