O'Reilly logo

Learning D by Michael Parker

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Error handling

D includes support for exception-based error handling. Another option is a popular feature called the scope statement.

Scope guards

In a C function that manipulates a locally allocated buffer, it's not unusual to see a series of if…else blocks where, after the failure of some operation, either the buffer is freed directly or via a goto statement. In D, we need neither idiom:

void manipulateData() {
  import core.stdc.stdlib : malloc, free;
  auto buf = cast(ubyte*)malloc(1024);
  scope(exit) if(buf) free(buf);
  // Now do some work with buf
}

Here, memory is allocated outside the GC with malloc and should be released when the function exits. The highlighted scope(exit) allows that. Scope statements are executed at the end of any scope in ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required