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.stdio
forwriteln
andstd.format
forformat
.Instead of a struct, we define a custom exception class
ArgException
that inherits from the built-inException
class.The
Error()
method is replaced by the constructor of our custom exception class. In D, the error message is typically stored in themsg
property of theException
class.The
f
function now throws anArgException
instead of returning an error.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.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 generalException
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.