在我的 C# 代码中显示错误 "A previous catch clause already catches all exceptions of this or a super type `System.Exception' "

Showing the error "A previous catch clause already catches all exceptions of this or a super type `System.Exception' " in my C# code

在我的 C# 代码中显示错误 "A previous catch clause already catch clause already catches all exceptions of this or a super type `System.Exception' "

using System;   
class Test { 
    static void Main()  { 
        try{ 
            int a=10,b=0,c=0;c=a/b ; 
            Console.WriteLine(c);
        }   
        catch(System.Exception e) { 
            Console.WriteLine(e.Message); 
        } 
        catch(System.DivideByZeroException ex) {  
            Console.WriteLine(ex.Message); 
        } 
    } 
}

异常处理程序按从上到下的顺序处理,只调用第一个匹配的异常处理程序。因为您的第一个处理程序捕获 System.Exception,并且所有异常都派生自 System.Exception,它会捕获所有内容,而第二个处理程序永远不会执行。

多个异常处理程序的最佳做法是将它们从特定到一般排序,如下所示:

using System;   
class Test { 
    static void Main()  { 
        try{ 
            int a=10,b=0,c=0;c=a/b ; 
            Console.WriteLine(c);
        }   
        catch(System.DivideByZeroException ex) {  
            Console.WriteLine(ex.Message); 
        } 
        catch(System.Exception e) { 
            Console.WriteLine(e.Message); 
        } 
    } 
}

如果您绝对肯定必须首先处理 System.Exception(尽管我想不出原因),您可以编写一个异常过滤器以允许 DivideByZero 通过,如下所示:

using System;   
class Test { 
    static void Main()  { 
        try{ 
            int a=10,b=0,c=0;c=a/b ; 
            Console.WriteLine(c);
        }   
        catch(System.Exception e) 
        when (!(e is DivideByZeroException)){ 
            Console.WriteLine(e.Message); 
        } 
        catch(System.DivideByZeroException ex) {  
            Console.WriteLine(ex.Message); 
        } 
    } 
}

注意:根据 MSDN,you should avoid catching general exception types like System.Exception