This documentation is archived and is not being maintained.

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.

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}.", inFile)
            Throw
            End Try

        End Sub

    End Class

End Namespace

Show: