CA1031 : Ne pas intercepter des types d'exception généraleCA1031: Do not catch general exception types

TypeNameTypeName DoNotCatchGeneralExceptionTypesDoNotCatchGeneralExceptionTypes
CheckIdCheckId CA1031CA1031
CategoryCategory Microsoft.DesignMicrosoft.Design
Modification avec ruptureBreaking Change Sans ruptureNon-breaking

CauseCause

Une exception générale comme System.Exception ou System.SystemException est interceptée dans un catch instruction ou une clause catch générale comme catch() est utilisé.A general exception such as System.Exception or System.SystemException is caught in a catch statement, or a general catch clause such as catch() is used.

Description de la règleRule description

Les exceptions générales ne doivent pas être interceptées.General exceptions should not be caught.

Comment corriger les violationsHow to fix violations

Pour corriger une violation de cette règle, interceptez une exception plus spécifique ou levez à nouveau l’exception générale en tant que la dernière instruction dans le catch bloc.To fix a violation of this rule, catch a more specific exception, or rethrow the general exception as the last statement in the catch block.

Quand supprimer les avertissementsWhen to suppress warnings

Ne supprimez aucun avertissement de cette règle.Do not suppress a warning from this rule. Interception de types d’exception générale peut masquer des problèmes d’exécution à partir de l’utilisateur de la bibliothèque et peut compliquer le débogage.Catching general exception types can hide run-time problems from the library user and can make debugging more difficult.

Note

En commençant par le .NET Framework 4.NET Framework 4, le common language runtime (CLR) n’envoie plus d’exceptions d’état endommagé qui se produisent dans le système d’exploitation et le code managé, telles que des violations d’accès dans WindowsWindows, pour être gérées par le code managé.Starting with the .NET Framework 4.NET Framework 4, the common language runtime (CLR) no longer delivers corrupted state exceptions that occur in the operating system and managed code, such as access violations in WindowsWindows, to be handled by managed code. Si vous voulez compiler une application dans le .NET Framework 4.NET Framework 4 ou versions ultérieures et maintenir gestion des exceptions d’état endommagé, vous pouvez appliquer le HandleProcessCorruptedStateExceptionsAttribute d’attribut à la méthode qui gère l’exception d’état endommagé.If you want to compile an application in the .NET Framework 4.NET Framework 4 or later versions and maintain handling of corrupted state exceptions, you can apply the HandleProcessCorruptedStateExceptionsAttribute attribute to the method that handles the corrupted state exception.

ExempleExample

L’exemple suivant montre un type qui enfreint cette règle et un type qui implémente correctement le catch bloc.The following example shows a type that violates this rule and a type that correctly implements the catch block.

using namespace System;
using namespace System::IO;

namespace DesignLibrary
{
    // Creates two violations of the rule.
    public ref 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(Exception^ e)
            {
                Console::WriteLine("Unable to open {0}.", outFile);
            }
        }
    };

    public ref 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(Exception^ e)
            {
                Console::WriteLine("Unable to open {0}.", outFile);
                throw;
            }
        }
    };
}
Imports System
Imports System.IO

Namespace DesignLibrary

    ' Creates two violations of the rule.
    Public Class GenericExceptionsCaught

        Dim inStream  As FileStream 
        Dim outStream As FileStream 

        Sub New(inFile As String, outFile As String)

            Try
                inStream = File.Open(inFile, FileMode.Open)
            Catch ex As SystemException
                Console.WriteLine("Unable to open {0}.", inFile)
            End Try

            Try
                outStream = File.Open(outFile, FileMode.Open)
            Catch
                Console.WriteLine("Unable to open {0}.", outFile)
            End Try

        End Sub

    End Class

    Public Class GenericExceptionsCaughtFixed

        Dim inStream  As FileStream 
        Dim outStream As FileStream 

        Sub New(inFile As String, outFile As String)

            Try
                inStream = File.Open(inFile, FileMode.Open)

            ' Fix the first violation by catching a specific exception.
            Catch ex As FileNotFoundException
                Console.WriteLine("Unable to open {0}.", inFile)
            End Try

            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
            End Try

        End Sub

    End Class

End Namespace
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;
            }
        }
    }
}

CA2200 : Levez à nouveau une exception pour conserver les détails de la pileCA2200: Rethrow to preserve stack details