Tricky code with exceptions

Brad Anderson eco at gnuk.net
Thu May 9 11:24:44 PDT 2013


On Thursday, 9 May 2013 at 11:24:03 UTC, bearophile wrote:
> A little Java program I've just found in a blog post:
>
>
> class Flow {
>     static public void main(String[] args) {
>         for (int i = 0; i < 6; ++i) {
>             System.out.println("Loop: " + i);
>
>             try {
>                 try {
>                     if (i == 3)
>                         break;
>                 } finally {
>                     if (i % 2 != 0)
>                         throw new Exception("");
>                 }
>             } catch (Exception e) {
>                 System.out.println("Caught");
>             }
>         }
>     }
> }
>
>
> Its output:
>
> Loop: 0
> Loop: 1
> Caught
> Loop: 2
> Loop: 3
> Caught
> Loop: 4
> Loop: 5
> Caught
>
>
> My D translation:
>
> import std.stdio;
>
> void main() {
>     foreach (i; 0 .. 6) {
>         writeln("Loop: ", i);
>
>         try {
>             try {
>                 if (i == 3)
>                     break;
>             } finally {
>                 if (i % 2 != 0)
>                     throw new Exception("");
>             }
>         } catch (Exception e) {
>             writeln("Caught");
>         }
>     }
> }
>
>
> It prints:
>
> Loop: 0
> Loop: 1
> Caught
> Loop: 2
> Loop: 3
>
> And then it crashes.
>
> Bye,
> bearophile


I just tested this for you when you hopped in IRC but you left 
before I could tell you that a 64-bit Windows dmd build did not 
crash and here is the output.

Loop: 0
Loop: 1
Caught
Loop: 2
Loop: 3
Caught
Loop: 4
Loop: 5
Caught


More information about the Digitalmars-d-learn mailing list