C# Error CS0160 – A previous catch clause already catches all exceptions of this or of a super type (‘type’)

C# Compiler Error

CS0160 – A previous catch clause already catches all exceptions of this or of a super type (‘type’)

Reason for the Error

You will receive this error when one of the catch blocks that you have defined previous to the current one already catches the Exception. All the catch statements especially when you have defined multiple catch blocks should always be in decreasing order of deviation.

The below code snippet demonstrates the C# error code CS0160 as the catch block with Exception parameter always be caught and hence it should be defined after the DivideByZeroException.

using System;

namespace ConsoleApp2
{
    class Program
    {
        public static void Main()
        {
           try
            { 

            }
            catch(Exception ex)
            {

            }
            catch(DivideByZeroException ex)
            {

            }


        }

    }
    
}
C#-S-5: if-else condition
C# Error CS0160 – A previous catch clause already catches all exceptions of this or of a super type ('type')

Error CS0160 A previous catch clause already catches all exceptions of this or of a super type (‘Exception’) ConsoleApp2 C:\Users\Senthil\source\repos\ConsoleApp1\ConsoleApp2\Program.cs 17 Active

Solution

Ensure that the series of catch blocks that you define is always in the decreasing order of its inheritance. In the above example, DivideByZeroException should always be first and then followed by Exception class in the catch block.