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:
We import
std.stdioforwritelnandstd.formatforformat.Instead of a struct, we define a custom exception class
ArgExceptionthat inherits from the built-inExceptionclass.The
Error()method is replaced by the constructor of our custom exception class. In D, the error message is typically stored in themsgproperty of theExceptionclass.The
ffunction now throws anArgExceptioninstead of returning an error.In the
mainfunction, we use a try-catch block to handle the exception. This is equivalent to checking for errors in the original code.D doesn’t have an exact equivalent to
errors.As. Instead, we can directly catch our specific exception type and access its properties.If the caught exception doesn’t match
ArgException, it will be caught by the generalExceptioncatch 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 itThis example shows how D handles custom errors through exceptions, providing a similar functionality to the custom error types in the original code.