Compartir a través de


CA1031: No capturar los tipos de excepción general

Nombre de tipo

DoNotCatchGeneralExceptionTypes

Identificador de comprobación

CA1031

Categoría

Microsoft.Design

Cambio problemático

Poco problemático

Motivo

Una excepción general como System.Exception o System.SystemException se detecta en una instrucción catch o se utiliza una cláusula catch general como catch().

Descripción de la regla

No se deben capturar excepciones generales.

Cómo corregir infracciones

Para corregir una infracción de esta regla, captura una excepción más específica, o vuelva a producir una excepción general como la última instrucción del bloque catch.

Cuándo suprimir advertencias

No suprima las advertencias de esta regla.Capturar tipos de excepciones generales puede ocultar los problemas en tiempo de ejecución del usuario de la biblioteca y pueden dificultar la depuración.

[!NOTA]

A partir de .NET Framework 4, Common Language Runtime (CLR) ya no proporciona excepciones de estado corruptas que aparecen en el sistema operativo y el código administrado, como infracciones de acceso en Windows, para ser manejadas mediante código administrado. Si desea compilar una aplicación en .NET Framework 4 (o posterior) y mantener el control de las excepciones de estado corruptas, puede aplicar el atributo HandleProcessCorruptedStateExceptionsAttribute al método que administra la excepción de estado corrupta.

Ejemplo

El ejemplo siguiente muestra un tipo que infringe esta regla y un tipo que implementa correctamente el bloque catch.

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

Reglas relacionadas

CA2200: Iniciar de nuevo para preservar los detalles de la pila