C# 代码异常

C# code exceptions

我是 c# 的初学者,我不知道这段代码有什么问题,需要一点帮助

        try 
        {
            double[,] matrix = new double[2,2];
            String liczba = "85481";
            matrix[1,1] = double.Parse(liczba); 
        }

        catch (Exception)
        {
            Console.WriteLine ("general exception");
        }
        catch (OverflowException)
        {
            Console.WriteLine ("exceeded scope of variable");
        }

        catch (FormatException)
        {
            Console.WriteLine ("variable converstion error");
        }

编译器在这里帮了您一些忙。您将遇到两个如下所示的错误:

A previous catch clause already catches all exceptions of this or of a super type ('System.Exception')

您无法在不太具体的类型之后捕捉到更具体的 Exception 类型。来自 C# reference,强调我的:

... the order of the catch clauses is important because the catch clauses are examined in order. Catch the more specific exceptions before the less specific ones. The compiler produces an error if you order your catch blocks so that a later block can never be reached.

所有异常都来自 Exception (System.Exception)。将它们重新排序以将 Exception 的处理程序作为最后一个 catch 子句,它将编译:

try
{
    double[,] matrix = new double[2, 2];
    String liczba = "85481";
    matrix[1, 1] = double.Parse(liczba);
}        
catch (OverflowException)
{
    Console.WriteLine("exceeded scope of variable");
}
catch (FormatException)
{
    Console.WriteLine("variable converstion error");
}
catch (Exception)
{
    Console.WriteLine("general exception");
}