Custom Errors in D Programming Language

import std.stdio;
import std.format;

// A custom error type usually has the suffix "Exception".
class ArgException : Exception
{
    int arg;

    this(int arg, string message)
    {
        super(format("%d - %s", arg, message));
        this.arg = arg;
    }
}

int f(int arg)
{
    if (arg == 42)
    {
        // Throw our custom exception.
        throw new ArgException(arg, "can't work with it");
    }
    return arg + 3;
}

void main()
{
    try
    {
        int result = f(42);
    }
    catch (ArgException ae)
    {
        // In D, we can directly access the exception properties
        writeln(ae.arg);
        writeln(ae.msg);
    }
    catch (Exception e)
    {
        writeln("Exception doesn't match ArgException");
    }
}

This D code demonstrates the concept of custom errors, which in D are implemented as exceptions. Here’s a breakdown of the changes and explanations:

  1. We import std.stdio for writeln and std.format for format.

  2. Instead of a struct, we define a custom exception class ArgException that inherits from the built-in Exception class.

  3. The Error() method is replaced by the constructor of our custom exception class. In D, the error message is typically stored in the msg property of the Exception class.

  4. The f function now throws an ArgException instead of returning an error.

  5. In the main function, we use a try-catch block to handle the exception. This is equivalent to checking for errors in the original code.

  6. D doesn’t have an exact equivalent to errors.As. Instead, we can directly catch our specific exception type and access its properties.

  7. If the caught exception doesn’t match ArgException, it will be caught by the general Exception catch block.

To run this program, save it as custom_errors.d and use the D compiler:

$ dmd custom_errors.d
$ ./custom_errors
42
42 - can't work with it

This example shows how D handles custom errors through exceptions, providing a similar functionality to the custom error types in the original code.