See:
Error Handling
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:
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)
{
}
|
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)
{
}
catch
{
try {
i = 5/v;
}
catch
{
}
}
try {
i = 5/v;
}
catch(StringException)
{
catch(FileException) {
}
}
try {
i = 5/v;
}
catch
{
}
catch(StringException)
{
}
|
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.
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
|