947
for the method to compile, no processing is performed to handle the thrown exceptions. Catch
statements that do not perform any processing will have unexpected results. In this case, this will
result in the return of a null String.
Example Language: Java (Bad)
public String readFile(String filename) {
String retString = null;
try {
// initialize File and FileReader objects
File file = new File(filename);
FileReader fr = new FileReader(file);
// initialize character buffer
long fLen = file.length();
char[] cBuf = new char[(int) fLen];
// read data from file
int iRead = fr.read(cBuf, 0, (int) fLen);
// close file
fr.close();
retString = new String(cBuf);
} catch (Exception ex) {
/* do nothing, but catch so it'll compile... */
}
return retString;
}
The catch statement should contain statements that either attempt to fix the problem, notify the
user that an exception has been raised and continue processing, or perform some cleanup and
gracefully terminate the program. The following Java example contains three catch statements.
The first of these will catch the FileNotFoundException that may be thrown by the FileReader
constructor called within the try/catch block. The second catch statement will catch the IOException
that may be thrown by the read method called within the try/catch block. The third catch statement
will catch all other exceptions thrown within the try block. For all catch statements the user is
notified that the exception has been thrown and the exception is rethrown to the block that called
the readFile() method for further processing or possible termination of the program. Note that with
Java it is usually good practice to use the getMessage() method of the exception class to provide
more information to the user about the exception raised.
Example Language: Java (Good)
public String readFile(String filename) throws FileNotFoundException, IOException, Exception {
String retString = null;
try {
// initialize File and FileReader objects
File file = new File(filename);
FileReader fr = new FileReader(file);
// initialize character buffer
long fLen = file.length();
char [] cBuf = new char[(int) fLen];
// read data from file
int iRead = fr.read(cBuf, 0, (int) fLen);
// close file
fr.close();
retString = new String(cBuf);
} catch (FileNotFoundException ex) {
System.err.println ("Error: FileNotFoundException opening the input file: " + filename );
System.err.println ("" + ex.getMessage() );
throw new FileNotFoundException(ex.getMessage());
} catch (IOException ex) {
System.err.println("Error: IOException reading the input file.\n" + ex.getMessage() );
throw new IOException(ex);
} catch (Exception ex) {
System.err.println("Error: Exception reading the input file.\n" + ex.getMessage() );
throw new Exception(ex);
}
CWE Version 4.14
CWE-391: Unchecked Error Condition
CWE-391: Unchecked Error Condition