D Documentation [ Log in ]
Error Handling
Error Handling in D is done via Exceptions. Exceptions are special objects that hold information about the error that occurred (in most cases this will be an error message like "File not found").

First, you would declare your own Exception like this:

class FileNotFoundException : Exception
{
  this(char[] msg)
  {
    super(msg);
  }
}


Declaring your own Exception type isn't neccessary, though. You can use the Exception class directly, but be aware that the code that wants to "catch" your exception will not be able to distinguish it from other Exception types.

If an error occurs, the program "throws" an exception:

throw new FileNotFoundException("I cant find the file " ~ filename);


The execution of code will stop at this point and if there is no "catch"-Statement for your exception then the program will exit.
Now, if you don't want your program to crash on a certain exception (perhaps because you expected that a function could fail and/or you want to handle the error yourself) you can use the "try/catch" statement. Let's assume the execption could get thrown during a function called ReadMyFile. If you want to catch it, you would write:
try {
  ReadMyFile(filename);
} catch (FileNotFoundException ex) {
  /* We caught the exception, now we can handle it */
  writefln("I couldn't read the file, but it doesn't really matter.");
  writefln("I will just go on with the normal program.");
}


There is but one problem with exceptions: Let's assume you write a function ReadFiles that allocates some memory without garbage collection (or it uses any type of resource that has to be freed again) and then calls the ReadMyFile function. Your function doesn't really bother if the file is present or not, but if an exception is thrown, you would have to free your resources!
You can easily accomplish that with the finally statement:
function ReadFiles()
{
  /* Allocate critical resources ... */
  try {
    ReadMyFile("foo.txt");
    ReadMyFile("bar.txt");
  }
  finally
  {
    /* Deallocate critical resources... */
  }
}

The statements in the finally block only get executed when any exeception is thrown during the try block.
PHP docwiki written by Markus Dangl. Best viewed with Mozilla Firefox.
This is the inofficial wiki for documenting the D programming language.
- Profiler -
Time for site generation: 0.0442 s