6 out of 9 rated this helpful - Rate this topic

Do not catch general exception types

TypeName

DoNotCatchGeneralExceptionTypes

CheckId

CA1031

Category

Microsoft.Design

Breaking Change

NonBreaking

System.Exception or System.SystemException is caught in a catch statement, or a general catch clause is used.

General exceptions should not be caught.

To fix a violation of this rule, catch a more specific exception, or re-throw the general exception as the last statement in the catch block.

Do not exclude a warning from this rule. Catching general exception types can hide run-time problems from the library user, and can complicate debugging.

The following example shows a type that violates this rule and a type that correctly implements the catch block.

using System;
using System.IO;

namespace DesignLibrary
{
    // Creates two violations of the rule.
    public class GenericExceptionsCaught
    {
        FileStream inStream;
        FileStream outStream;

        public GenericExceptionsCaught(string inFile, string outFile)
        {
            try
            {
                inStream = File.Open(inFile, FileMode.Open);
            }
            catch(SystemException e)
            {
                Console.WriteLine("Unable to open {0}.", inFile);
            }

            try
            {
                outStream = File.Open(outFile, FileMode.Open);
            }
            catch
            {
                Console.WriteLine("Unable to open {0}.", outFile);
            }
        }
    }

    public class GenericExceptionsCaughtFixed
    {
        FileStream inStream;
        FileStream outStream;

        public GenericExceptionsCaughtFixed(string inFile, string outFile)
        {
            try
            {
                inStream = File.Open(inFile, FileMode.Open);
            }

            // Fix the first violation by catching a specific exception.
            catch(FileNotFoundException e)
            {
                Console.WriteLine("Unable to open {0}.", inFile);
            }

            try
            {
                outStream = File.Open(outFile, FileMode.Open);
            }

            // Fix the second violation by re-throwing the generic 
            // exception at the end of the catch block.
            catch
            {
                Console.WriteLine("Unable to open {0}.", outFile);
                throw;
            }
        }
    }
}

Did you find this helpful?
(1500 characters remaining)
Community Content Add
Annotations FAQ
One basic reason is ..

When you use the catch and cast that as generic exception, it then compares with the following set of exceptions. Which is definitely an unwanted comparison or type conversion with the exact exception that is caught and caused by the code. Please refer to http://msdn.microsoft.com/en-us/library/system.exception.aspx for more about the exception class.

Microsoft.Build.BuildEngine..::.InternalLoggerException
Microsoft.Build.BuildEngine..::.InvalidProjectFileException
Microsoft.Build.BuildEngine..::.InvalidToolsetDefinitionException
Microsoft.Build.BuildEngine..::.RemoteErrorException
Microsoft.Build.Framework..::.LoggerException
Microsoft.JScript..::.CmdLineException
Microsoft.JScript..::.ParserException
Microsoft.ManagementConsole.Advanced..::.PrimarySnapInDataException
Microsoft.ManagementConsole.Internal..::.PrimarySnapInDataException
Microsoft.VisualBasic.ApplicationServices..::.CantStartSingleInstanceException
Microsoft.VisualBasic.ApplicationServices..::.NoStartupFormException
Microsoft.VisualBasic.Compatibility.VB6..::.WebClassContainingClassNotOptional
Microsoft.VisualBasic.Compatibility.VB6..::.WebClassCouldNotFindEvent
Microsoft.VisualBasic.Compatibility.VB6..::.WebClassNextItemCannotBeCurrentWebItem
Microsoft.VisualBasic.Compatibility.VB6..::.WebClassNextItemRespondNotFound
Microsoft.VisualBasic.Compatibility.VB6..::.WebClassUserWebClassNameNotOptional
Microsoft.VisualBasic.Compatibility.VB6..::.WebClassWebClassFileNameNotOptional
Microsoft.VisualBasic.Compatibility.VB6..::.WebClassWebItemNotValid
Microsoft.VisualBasic.Compatibility.VB6..::.WebItemAssociatedWebClassNotOptional
Microsoft.VisualBasic.Compatibility.VB6..::.WebItemClosingTagNotFound
Microsoft.VisualBasic.Compatibility.VB6..::.WebItemCouldNotLoadEmbeddedResource
Microsoft.VisualBasic.Compatibility.VB6..::.WebItemCouldNotLoadTemplateFile
Microsoft.VisualBasic.Compatibility.VB6..::.WebItemNameNotOptional
Microsoft.VisualBasic.Compatibility.VB6..::.WebItemNoTemplateSpecified
Microsoft.VisualBasic.Compatibility.VB6..::.WebItemTooManyNestedTags
Microsoft.VisualBasic.Compatibility.VB6..::.WebItemUnexpectedErrorReadingTemplateFile
Microsoft.VisualBasic.CompilerServices..::.IncompleteInitialization
Microsoft.VisualBasic.CompilerServices..::.InternalErrorException
Microsoft.VisualBasic.FileIO..::.MalformedLineException
System.AddIn.Hosting..::.AddInSegmentDirectoryNotFoundException
System.AddIn.Hosting..::.InvalidPipelineStoreException
System..::.ApplicationException
System.ComponentModel.Design..::.ExceptionCollection
System.Configuration.Provider..::.ProviderException
System.Configuration..::.SettingsPropertyIsReadOnlyException
System.Configuration..::.SettingsPropertyNotFoundException
System.Configuration..::.SettingsPropertyWrongTypeException
System.Data.Linq..::.ChangeConflictException
System.Diagnostics.Eventing.Reader..::.EventLogException
System.DirectoryServices.ActiveDirectory..::.ActiveDirectoryObjectExistsException
System.DirectoryServices.ActiveDirectory..::.ActiveDirectoryObjectNotFoundException
System.DirectoryServices.ActiveDirectory..::.ActiveDirectoryOperationException
System.DirectoryServices.ActiveDirectory..::.ActiveDirectoryServerDownException
System.DirectoryServices.Protocols..::.DirectoryException
System.IdentityModel.Selectors..::.CardSpaceException
System.IdentityModel.Selectors..::.IdentityValidationException
System.IdentityModel.Selectors..::.PolicyValidationException
System.IdentityModel.Selectors..::.ServiceBusyException
System.IdentityModel.Selectors..::.ServiceNotStartedException
System.IdentityModel.Selectors..::.StsCommunicationException
System.IdentityModel.Selectors..::.UnsupportedPolicyOptionsException
System.IdentityModel.Selectors..::.UntrustedRecipientException
System.IdentityModel.Selectors..::.UserCancellationException
System..::.InvalidTimeZoneException
System.IO.IsolatedStorage..::.IsolatedStorageException
System.IO.Log..::.SequenceFullException
System.Management.Instrumentation..::.InstrumentationBaseException
System.Management.Instrumentation..::.WmiProviderInstallationException
System.Net.Mail..::.SmtpException
System.Net.PeerToPeer..::.PeerToPeerException
System.Runtime.CompilerServices..::.RuntimeWrappedException
System.Runtime.Remoting.MetadataServices..::.SUDSGeneratorException
System.Runtime.Remoting.MetadataServices..::.SUDSParserException
System.Runtime.Serialization..::.InvalidDataContractException
System.Security.RightsManagement..::.RightsManagementException
System.ServiceModel.Channels..::.InvalidChannelBindingException
System..::.SystemException
System.Threading..::.LockRecursionException
System..::.TimeZoneNotFoundException
System.Web.Query.Dynamic..::.ParseException
System.Web.Security..::.MembershipCreateUserException
System.Web.Security..::.MembershipPasswordException
System.Web.UI..::.ViewStateException
System.Web.UI.WebControls..::.LinqDataSourceValidationException
System.Windows.Automation..::.NoClickablePointException
System.Windows.Automation..::.ProxyAssemblyNotLoadedException
System.Windows.Controls..::.PrintDialogException
System.Windows.Forms..::.AxHost..::.InvalidActiveXStateException
System.Windows.Xps..::.XpsException
System.Windows.Xps..::.XpsWriterException
System.Workflow.Activities.Rules..::.RuleException
System.Workflow.ComponentModel.Compiler..::.WorkflowValidationFailedException
System.Workflow.ComponentModel.Serialization..::.WorkflowMarkupSerializationException
System.Workflow.ComponentModel..::.WorkflowTerminatedException
System.Workflow.Runtime..::.WorkflowOwnershipException

FAQ: Why does FxCop warn against catch(Exception)?

See the following post on the Visual Studio Code Analysis blog:
http://blogs.msdn.com/fxcop/archive/2006/06/14/631923.aspx