try-catch-finally

C++ では try-catch しかなく finally が使えないが, D 言語では C# や Java のように finally も使える.

try_catch_finally.d

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import std.stdio;

class Foo{
  void open(){
    writeln("open");
    throw new Exception("error");
  }
  void close(){
    writeln("close");
  }
}

void main(){
  Foo x = new Foo;
  try{
    x.open(); // この中え例外発生
  }
  catch(Exception e){
    writeln(e);
  }
  finally{
    x.close();
  }
}

try_catch_finally.d の実行結果は:

[cactus:~/code_d/d_tuts]% ./try_catch_finally
open
object.Exception: error
----------------
5   try_catch_finally                   0x0000246b _Dmain + 43
6   try_catch_finally                   0x000140e3 extern (C) int rt.dmain2.main(int, char**) + 23
7   try_catch_finally                   0x0001401a extern (C) int rt.dmain2.main(int, char**) + 42
8   try_catch_finally                   0x0001412b extern (C) int rt.dmain2.main(int, char**) + 59
9   try_catch_finally                   0x0001401a extern (C) int rt.dmain2.main(int, char**) + 42
10  try_catch_finally                   0x00013fa7 main + 179
11  try_catch_finally                   0x00002435 start + 53
close

Previous topic

ref 関数

Next topic

static 属性