Panic in D Programming Language

import std.stdio;
import std.file;

void main()
{
    // We'll use assert throughout this site to check for
    // unexpected errors. This is the only program on the
    // site designed to fail an assertion.
    assert(false, "a problem");

    // A common use of assert is to abort if a function
    // returns an error value that we don't know how to
    // (or want to) handle. Here's an example of
    // asserting if we get an unexpected error when creating a new file.
    try
    {
        auto file = File("/tmp/file", "w");
    }
    catch (Exception e)
    {
        assert(false, e.msg);
    }
}

Running this program will cause it to fail an assertion, print an error message and stack trace, and exit with a non-zero status.

When the first assert in main fires, the program exits without reaching the rest of the code. If you’d like to see the program try to create a temp file, comment the first assert out.

$ rdmd panic.d
core.exception.AssertError@panic.d(9): a problem
----------------
??:? _d_assert [0x55a8a9541d30]
??:? _Dmain [0x55a8a95419b0]
??:? main [0x55a8a9541a30]
??:? _D2rt6dmain212_d_run_mainUiPPaPUAAaZiZ6runAllMFZ9__lambda1MFZv [0x55a8a9541f70]
??:? _d_run_main [0x55a8a9541ee0]
??:? main [0x55a8a9541e50]
??:? __libc_start_main [0x7f8f5c22ebf0]
??:? _start [0x55a8a9541859]

Note that unlike some languages which use exceptions for handling of many errors, in D it is idiomatic to use error-indicating return values wherever possible. However, for unexpected errors or programming mistakes, assertions are commonly used.

In D, assert is used for debugging and can be disabled in release builds, while enforce (from std.exception) is used for runtime checks that should always be active.