Total .NET Analyzer Rule Documentation  

EmptyCatch Rule

Review empty Catch statements to determine whether exception handling is needed.

Remarks

In general, you should use a Try. . . Catch block to handle exceptions by firing the specified action. By having no code in your Catch statement, you are not firing an action when an exception is encountered, and are instructing the application to continue executing after it encounters an exception.

This programming technique is valid in some cases. For example, if you have code that attempts to delete a file, it will generate an exception if the file doesn't exist. If you are not concerned with this exception, you can ignore any exceptions that occur on the file deletion by using an empty Catch statement, such as:


' VB
Try
System.IO.File.Delete "C:\TempFile.txt"
Catch
' Ignore the exception that is raised when the file doesn't exist
End Try

//C#
try
{
System.IO.File.Delete("C:\\TempFile.txt");
}
catch(Exception e)
{
// Ignore the exception that is raised when the file doesn't exist
}


You should, however, review any empty Catch statements in your code to determine whether exception handling is needed.

Resolution

If you have an empty Catch statement, you are effectively ignoring exceptions, thereby emulating the legacy Visual Basic On Error Resume Next error handling. You should examine all empty Catch statements to determine whether this is in fact appropriate, or whether exception handling is needed.

In most cases, you should consider adding code to handle the exception appropriately. Often, even simple exception handling (such as code to display or log the exception message) can make debugging errors in your application much more manageable. For example, if you simply want to display a message box with the exception message, you would use the following catch block:

' VB
Catch e As Exception
Console.WriteLine("An error occurred: '{0}'", e)

// C#
catch(Exception e)
{
Console.WriteLine("An error occurred: '{0}'", e);
}

See Also

Using the Try/Catch Block