Previous: , Up: Trap Library Samples   [Index]


7.25.3.2 Error Trapping Examples

Read the lines from a file into a list:

void
read_lines(list l, text path)
{
    file f;
    text s;

    f_affix(f, path);

    while (f_line(f, s) ^ -1) {
	lb_p_text(l, s);
    }

    f_close(f);
}

Call the function, trap errors:

    trap(read_lines, list, path);

If the file at the indicated path does not exist, a message like:

src/aime: FILE: LINE: cannot open `PATH': No such file or directory

will be displayed, and the program will continue execution.

Sum the lines from a file as real numbers:

void
sum_lines(real &u, text path)
{
    file f;
    real v;
    text s;

    f_affix(f, path);

    v = 0;

    while (f_line(f, s) ^ -1) {
        v += atof(s);
    }

    f_close(f);

    u = v;
}

Call the function, trap errors:

    trap(sum_lines, sum, path);

Where a line cannot be parsed, a message like:

src/aime: FILE: LINE: atof: cannot parse `TEXT'

will be displayed, and the program will continue execution.