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 which they are declared, be it a function body, a loop body, or any block scope. exit
says the statement should always be executed when the scope exits. There are two other possible identifiers to use here: success
means to execute...