Skip to content
Tutorials Center
My learning

Topics

Lesson 14 of 36 ยท Control Flow and Functions

Errors, Exceptions, Scope Guards and Contracts in D

Handle errors in D with try, catch and finally, clean up with scope(exit) and scope(failure), state preconditions with in and out contracts, and test code with unittest blocks.

Programs fail: files go missing, input is malformed, callers pass bad values. D gives you layers of defense. Exceptions report expected run-time problems. Scope guards clean up reliably. Contracts and assert state what must be true and catch programmer errors. Unit tests are built into the language. This lesson shows each tool and when to choose it. The D listings are read-only; the C stand-ins model the control flow in C.

Exceptions: try, catch, finally

D
import std.stdio;
import std.conv : to, ConvException;

int parseAge(string text)
{
    int age = text.to!int;                 // may throw ConvException
    if (age < 0)
    {
        throw new Exception("age cannot be negative");
    }
    return age;
}

void main()
{
    foreach (input; ["42", "abc", "-5"])
    {
        try
        {
            writeln("age: ", parseAge(input));
        }
        catch (ConvException e)
        {
            writeln("not a number: ", input);
        }
        catch (Exception e)
        {
            writeln("problem: ", e.msg);
        }
        finally
        {
            writeln("done with ", input);
        }
    }
}

The loop prints age: 42, then not a number: abc, then problem: age cannot be negative, each followed by a done with ... line from finally. Catch more specific exception types first. All exceptions derive from Throwable; Exception is for recoverable problems, and Error (for example an array bounds violation or a failed assert) means a bug and normally should not be caught. Create your own with class AppException : Exception { this(string m) { super(m); } }.

Scope guards

scope(exit), scope(success) and scope(failure) schedule code to run when the current scope ends, in reverse order of declaration. They put cleanup next to the thing it cleans up:

D
import std.stdio;

void process()
{
    writeln("open");
    scope(exit) writeln("close");           // always runs
    scope(failure) writeln("rolled back");  // only on exception
    scope(success) writeln("committed");    // only on normal exit

    writeln("working");
    // throw new Exception("boom");         // try uncommenting
}

Run normally, it prints open, working, committed, close: guards run in reverse order, so committed (declared last) comes before close. With the throw enabled, you would see rolled back and close instead. This replaces many try/finally blocks and the goto cleanup; pattern of C.

assert and contracts

assert(condition, message) documents and checks something that must be true. A failing assert is a bug and throws an AssertError. Contracts make this part of a function's interface:

D
double sqrtOf(double x)
in (x >= 0, "x must not be negative")        // precondition
out (r; r >= 0)                              // postcondition on the result
{
    import std.math : sqrt;
    return sqrt(x);
}

struct Account
{
    private int balance;
    invariant (balance >= 0);                 // class/struct invariant

    void withdraw(int amount)
    in (amount > 0)
    {
        balance -= amount;
    }
}

in checks inputs when the function is called, out checks the result when it returns, and invariant runs around public member calls. Contracts are on in normal builds and removed by -release. Use exceptions for conditions that can happen when the program is correct (bad user input, missing file), and contracts for conditions that mean the caller has a bug.

Built-in unit tests

A unittest block sits next to the code it tests and runs when you compile with -unittest (or dub test):

D
int clamp(int v, int lo, int hi)
{
    return v < lo ? lo : (v > hi ? hi : v);
}

unittest
{
    assert(clamp(5, 0, 10) == 5);
    assert(clamp(-3, 0, 10) == 0);
    assert(clamp(99, 0, 10) == 10);
}

No framework is needed. A failure reports the file and line of the assert.

C stand-ins for error handling

C has no exceptions, so errors travel through return codes, and cleanup is hand-written. These stand-ins show the equivalent shape.

C C stand-in: error codes instead of exceptions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The output matches the D loop: three result lines, each followed by done with ....

C C stand-in: cleanup in reverse order like scope guards

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

It prints open, working, committed, close. D tracks this stack for you and decides which guards run based on how the scope ended.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. In which order do scope(exit) guards run?

    The most recently declared guard runs first.
  2. 2. When should you use a contract (in) instead of an exception?

    Contracts state what callers must guarantee; breaking them is a programming error.
  3. 3. What does scope(failure) run on?

    scope(failure) is for rollback on exceptions.
  4. 4. How do you run unittest blocks?

    The -unittest flag compiles and runs them.

Summary

  • Use try/catch/finally for expected run-time errors and throw to report them.
  • scope(exit), scope(success) and scope(failure) put cleanup beside the allocation.
  • assert, in, out and invariant catch programmer errors; -release removes them.
  • unittest blocks give every module built-in tests.

Next: Arrays: static and dynamic