捕捉错误(1)

来源:百度文库 编辑:神马文学网 时间:2024/04/27 15:18:20
1 捕捉错误(1)
为了通知调用者参数是无效的,int.Parse()会引发异常(throw an exception)。引发异常会终止执行当前分支,并跳到调用栈中用于处理异常的第一个代码块。
但是,由于当前尚未提供任何异常处理,所以程序会向用户报告遇到了一个未处理的异常(unhandled exception)。假定系统中没有注册任何调试器,错误信息就会出现在控制台上,如输出4-12所示。
输出4-12
Hey you!
Enter your first name: Inigo
Enter your age: forty-two Unhandled Exception: System.FormatException: Input string was
not in a correct format.
at System.Number.ParseInt32(String s, NumberStyles style,
NumberFormatInfo info)
at ExceptionHandling.Main()
显然,像这样的错误消息并不是特别有用。为了解决这个问题,有必要提供一个机制对错误进行恰当的处理,例如向用户报告一条更有意义的错误消息。
这个过程称为捕捉异常(catching an exception)。代码清单4-18展示了具体的语法,输出4-13展示了结果。
代码清单4-18 捕捉异常
using System; class ExceptionHandling
{
static int Main()
{
string firstName;
string ageText;
int age;
int result = 0;       Console.Write("Enter your first name: ");
firstName = Console.ReadLine();       Console.Write("Enter your age: ");
ageText = Console.ReadLine();       try
{
age = int.Parse(ageText);
Console.WriteLine(
"Hi {0}! You are {1} months old.",
firstName, age*12);
}
catch (FormatException )
{
Console.WriteLine(
"The age entered, {0}, is not valid.",
ageText);
result = 1;
}
catch(Exception exception)
{
Console.WriteLine(
"Unexpected error: {0}", exception.Message);
result = 1;
}
finally
{
Console.WriteLine("Goodbye {0}",
firstName);
}
return result;
}
}
输出4-13
Enter your first name: Inigo
Enter your age: forty-two
The age entered, forty-two, is not valid.
Goodbye Inigo
首先,要用一个try块将可能引发异常的代码(age = int.Parse())包围起来。这个块是从一个try关键字开始的。try关键字告诉编译器:开发者认为块中的代码有可能引发一个异常;如果真的引发了异常,那么某个catch块就要尝试处理这个异常。
在一个try块之后,必须紧跟着一个或多个catch块(或一个finally块)。在catch块的标头(参见本章稍后的“高级主题:泛化catch”)中,可以选择指定异常的数据类型。只要数据类型与异常类型匹配,对应的catch块就会执行。但是,假如一直找不到合适的catch块,引发的异常就会变成一个未处理的异常,就好像没有进行异常处理一样。
图4-1展示了最终的程序流程。


(点击查看大图)图4-1 异常处理程序流程