Skip to content

Empty Catch Block

What does this mean ?

Catch blocks in a Try and Catch statement should contain code to handle the thrown error. The Exception will not be addressed if they are empty or simply include comments. Empty catch blocks indicate that a programmer is unsure what to do with an exception. They are preventing an exception from rising up from the try block.

What can happen ?

Empty catch blocks are considered a business risk since they might cause security difficulties. Risks might include programmers and/or the firm being unaware that their security has been hacked.

Recommendation

  • Catch blocks should include code to handle any exceptions that are thrown.

Sample Code

Vulnerable :

string text = "";
try
{
  text = File.ReadAllText(fileName);
}
catch (Exception exc) 
{
  //logger.Log(exc); // Noncompliant
}

Non Vulnerable :

string text = "";
try
{
    text = File.ReadAllText(fileName);
}
catch (Exception exc)
{
    logger.Log(exc); // Compliant
}

Vulnerable :

try {
  rs = stmt.executeQuery(query);
}
catch(SQLException e) {
  //log(e); // Noncompliant
}

Non Vulnerable :

try {
  rs = stmt.executeQuery(query);
}
catch(SQLException e) {
  log(e); // Compliant
}

Vulnerable :

try {
  foo(); // Non Compliant
} catch (SomeCustomException $e) { 
  //echo $e->getMessage(); // Non Compliant
}{code}

Non Vulnerable :

try {
  foo(); 
} catch (SomeCustomException $e) { 
  echo $e->getMessage(); // Compliant
}{code}

Vulnerable :

try { 
  callback(); 
} catch (e) {
  // Vulnerable
}

Non Vulnerable :

try { 
  callback(); 
} catch (e) {
  console.log("Failed to run", e); // Non Vulnerable
}

References