Tricky code with exceptions

bearophile bearophileHUGS at lycos.com
Thu May 9 04:24:02 PDT 2013


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


More information about the Digitalmars-d-learn mailing list