946
// allocate memory
char *buffer = new char [length];
// read data from file
infile.read (buffer,length);
if (!infile.good()) {
throw "Unable to read from file " + filename;
}
infile.close();
return buffer;
}
catch (...) {
/* bug: insert code to handle this later */
}
}
The catch statement should contain statements that either attempt to fix the problem or notify the
user that an error has occurred and continue processing or perform some cleanup and gracefully
terminate the program. The following C++ example contains two catch statements. The first of
these will catch a specific error thrown within the try block, and the second catch statement will
catch all other errors from within the catch block. Both catch statements will notify the user that
an error has occurred, close the file, and rethrow to the block that called the readFile() method for
further handling or possible termination of the program.
Example Language: C++ (Good)
char* readFile (char *filename) {
try {
// open input file
ifstream infile;
infile.open(filename);
if (!infile.is_open()) {
throw "Unable to open file " + filename;
}
// get length of file
infile.seekg (0, ios::end);
int length = infile.tellg();
infile.seekg (0, ios::beg);
// allocate memory
char *buffer = new char [length];
// read data from file
infile.read (buffer,length);
if (!infile.good()) {
throw "Unable to read from file " + filename;
}
infile.close();
return buffer;
}
catch (char *str) {
printf("Error: %s \n", str);
infile.close();
throw str;
}
catch (...) {
printf("Error occurred trying to read from file \n");
infile.close();
throw;
}
}
Example 3:
In the following Java example the method readFile will read the file whose name is provided in the
input parameter and will return the contents of the file in a String object. The constructor of the
FileReader object and the read method call may throw exceptions and therefore must be within
a try/catch block. While the catch statement in this example will catch thrown exceptions in order
CWE Version 4.14
CWE-390: Detection of Error Condition Without Action
CWE-390: Detection of Error Condition Without Action