C# - 例外 - 有两种可能的例外,取决于条件 [英] C# - exceptions - there are two possible exceptions, dependning on the conditon

查看:137
本文介绍了C# - 例外 - 有两种可能的例外,取决于条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述





我正在回答这个问题,有两种可能的例外,具体取决于条件。问题是:



系统已生成一组5个员工姓名,但他们可能是错误。返回数组中的第4个名称,但要注意有两个可能的问题

如果

数组中没有足够的元素,返回数组无效长度,任何其他例外应返回腐败数据。




请参阅下面的代码。我相信'catch'部分内部的部分是我出错的地方,但我需要帮助修复它。谢谢。



亲切的问候



我的尝试:



Hi,

I am answering this questions where there are two possible exceptions, depending on a condition. The question is:

The system has generated a set of 5 employee names, but their may be bugs. Return the 4th name from the array, but be careful there is two possible problems
if
the array does not contain enough elements, return "Array not valid length", any other exception should return "Corrupt Data".


Please see my code below. I believe the part inside the 'catch' part is where I've gone wrong but I need help fixing it. Thanks.

Kind regards

What I have tried:

  public static string PointOfFailure(string[] employeeNames)
        {

            try
            {

                return employeeNames[3];

            }

            catch (Exception)

            {

                if (employeeNames.Length > 5)
                { return "Array not valid length"; }

                return "Corrupt Data";

            }


        }
    }
}

推荐答案

<pre lang="c#">

public static string PointOfFailure(string [] employeeNames)

{



试试

{



return employeeNames [3];



}



catch(System.IndexOutOfRangeException e)



{

return数组无效长度;

}

catch(例外)



{

returnCorrupt Data ;

}



}

}

}多个catch块可以在那里,处理特定的类型,如

public static string PointOfFailure(string[] employeeNames)
{

try
{

return employeeNames[3];

}

catch (System.IndexOutOfRangeException e)

{
return "Array not valid length";
}
catch (Exception)

{
return "Corrupt Data";
}

}
}
} multiple catch blocks can be there, on to handle specific type like

System.IndexOutOfRangeException

。其他用于保留所有。


这篇关于C# - 例外 - 有两种可能的例外,取决于条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆