Skip to content

Empty Catch Block

What does this mean ?

In a Try and Catch statement, Catch blocks should have code to handle the thrown exception. If they are empty or only contain comments, the Exception will not be handled. Empty catch blocks are an indication of a programmer not knowing what to do with an exception. They are suppressing the exception from possibly bubbling up from the try block.

What can happen ?

Empty catch blocks are considered a risk from a business perspective as it can pose security issues. Risks can involve programmers and/or the company are unaware of the security being compromised.

Recommendation

  • Catch blocks should have code to handle the thrown exception.

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}

References