软件开发中,不可避免的会遇到异常,有些异常便于开发人员快速捕获错误,修改程序;有些异常,需要提示友好。(给用户的 异常)
异常处理方法
一:通常处理方法
异常处理方法就是在代码中加入 try{} catch{} finally{} 程序块
二:多catch异常处理
在实际操作中,一段代码可能会有多个位置出现异常,如果我们使用一个try就无法准确的thow出异常,
那么,我们可以应用try 多 catch 来完成不同类型的异常处理:如下代码:
string[] arr ={ "1","2","3"};
string str = tbInput.Text.Trim();
try
{
int index = Convert.ToInt32(str);
if (index > 5)
{
Response.Write(arr[index]);
}
}
catch (FormatException ex)
{
throw new Exception("数据类型错误!");
}
catch (IndexOutOfRangeException ex)
{
throw new Exception("超过数组Index!");
}
catch
{
throw new Exception("other exception");
}
string str = tbInput.Text.Trim();
try
{
int index = Convert.ToInt32(str);
if (index > 5)
{
Response.Write(arr[index]);
}
}
catch (FormatException ex)
{
throw new Exception("数据类型错误!");
}
catch (IndexOutOfRangeException ex)
{
throw new Exception("超过数组Index!");
}
catch
{
throw new Exception("other exception");
}
在例子中,代码段可能会遇到两种异常:数据类型错误、Index错误,那么,我们就分别通过不同类型的Excaption来处理。