Behavioral Attributes: nothrow and @nogc

Explore the nothrow and @nogc behavioral attributes of functions.

We'll cover the following

nothrow functions

We discussed the exception mechanism in the exceptions chapter.

It would be good practice for functions to document the types of exceptions that they might throw under specific error conditions. However, as a general rule, callers should assume that any function can throw any exception.

Sometimes it is more important to know that a function does not emit any exception at all. For example, some algorithms can take advantage of the fact that certain steps cannot be interrupted by an exception. nothrow guarantees that a function does not emit any exception:

int add(int lhs, int rhs) nothrow {
    // ...
}

Note: Remember that catching Error or its base class Throwable is not recommended to. Additionally, “any exception” means “any exception that is defined under the exception hierarchy.” A nothrow function can still emit exceptions that are under the Error hierarchy, which represents irrecoverable error conditions that should preclude the program from continuing its execution.

Such a function can neither throw an exception itself nor can call a function that may throw an exception:

int add(int lhs, int rhs) nothrow { 
    writeln("adding"); // ← compilation ERROR
    return lhs + rhs;
}

The compiler rejects the code because add() violates the no-throw guarantee:

Error: function 'deneme.add' is nothrow yet may throw

This is because writeln is not (and cannot be) a nothrow function.

The compiler can infer that a function can never emit an exception. The following implementation of add() is nothrow because it is obvious to the compiler that the try-catch block prevents any exception from escaping the function:

Get hands-on with 1400+ tech skills courses.