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 ...

Get Learning D now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.