Error Codes
The return value 0 from a method may show that there was some error, but not what the problem was. It is common to combine return values of this kind with a way to find out the nature of the problem. This can be done with special error codes, that your program can retrieve from somewhere. Lets look at this example, which opens a file on disk for reading:
Stdio.File localfile = Stdio.File();
if (!localfile->open(file_name, "r"))
{
werror("Couldn't open '" + file_name + "'.\n");
werror(strerror(localfile->errno()) +
" (errno = " + localfile->errno() + ").\n");
exit(1);
}
Some comments about this:
Stdio.Fileis a stream that can be used to read from a file on fisk. It is similar to the data type
FILEin C, and the classesifstreamandofstreamin C++.!localfile->open(file_name, "r")means exactly the same thing as
localfile->open(file_name, "r") == 0It is common to use the logical not operator (
!) to check if something is 0.errnois a method in the classStdio.File, and can be used io check what kind of error has occurred in a particular stream. It returns an error code.errnois not a global variable, as in C.strerrorreturns a string that describes the error number given as an argument.
If the file couldn’t be opened, the program’s output will look something like this:
Couldn't open 'foobar.txt'.
No such file or directory (errno = 2).