...

/

The try-catch Statement to Catch Exceptions

The try-catch Statement to Catch Exceptions

This lesson explains how we can use try-catch statements to catch exceptions.

The try-catch statement to catch exceptions #

As we’ve seen earlier in this chapter, a thrown exception causes the program execution to exit all functions, and this finally terminates the whole program.
The exception object can be caught by a try-catch statement at any point on its path as it exits the functions. The try-catch statement models the phrase “try to do something, and catch exceptions that may be thrown.” Here is the syntax of try-catch:

try {
    // the code block that is being executed, where an exception may be thrown
} catch (an_exception_type) {
    // expressions to execute if an exception of this type is caught
} catch (another_exception_type) {
    // expressions to execute if an exception of this other type is caught

// ... more catch blocks as appropriate ...
} finally {
    // expressions to execute regardless of whether an exception is thrown
}

Let’s start with the following program, which does not use a try-catch statement at this stage. The program reads the value of a die from a file and writes its value to the standard output:

Press + to interact
// this program is expected to fail execution
import std.stdio;
int readDieFromFile() {
auto file = File("the_file_that_contains_the_value", "r");
int die;
file.readf(" %s", &die);
return die;
}
void main() {
const int die = readDieFromFile();
writeln("Die value: ", die);
}

Note that the readDieFromFile function is written in a way that ignores error conditions, assuming that the file and the value that it contains are available. In other words, the function is dealing only with its own task instead of paying attention to error conditions. This is a benefit of using exception handling: many functions can be written ...