D Documentation  
Try statement
See: Error Handling

try
{
  /* statements that could throw an exception */

}

If there occurrs an exception between the brackets of try, the program will not halt, but keep on running after the whole statement.
The catch statement is used to describe, what should happen if there was an exception:

try
{
  /* exception? */
}
catch
{
  /* only executed if there occurred an exception */
}

You should avoid using catch this way, when your program does not give a good routine for any possible exception.
Sometimes it is very useful to do different things when different exceptions have been thrown.

try
{
  /* ? */
}
catch(exc_type)
{
  /* only executed if exc_type was thrown */
}

This way, you can decide what to do if there was exactly the exception of type exc_type thrown.
Note: It is illegal to create a catch in a catch!

Example:
int i = 0;
int v = 0;
try {
  i     = 5/v;
}
catch(StringException)
{
  /* valid */
}
catch
{
  try {
    i = 5/v;
  }
  catch
  {
    /* valid */
  }
}

try {
  i     = 5/v;
}
catch(StringException)
{
  catch(FileException) {
    /* invalid */
  }
}

try {
  i     = 5/v;
}
catch
{
  /* valid */
}
catch(StringException)
{
  /* invalid */
}

In addition you can place a finally statement after try or catch to do things that must be done :-)
For example to close the file if there was a read error.

try
{
  /* exception? */
}
finally
{
  /* this will be executed anyways */
}

Example:
int i = 0;
try {
  int v = 0;
  i     = 5/v;
} catch {
  i = -1;
  writefln("Exception catched!");
} finally
  writefln("Result is %d",i);

Output:
Exception catched!
Result is -1


See also:
Throw statement
Created using PHP docwiki written by Markus Dangl. Best viewed with Mozilla Firefox.