C# 抛出和捕获异常
- 格式:doc
- 大小:47.50 KB
- 文档页数:2
//除数异常
Console.WriteLine("请输入数字a");
inta=Convert.ToInt32(Console.ReadLine());
try
{
stringstr=null;
PrintString(str);
}
catch(ArgumentExceptione)
{
Console.WriteLine("第一个异常:"+e.Message);
}
catch(Exceptione)
{
Console.WriteLine("第二个异常:"+e.Message);
thrownewArgumentException("字符串不能为空!");
}
(4)在try块下放置两个catch块捕获可能发生的异常。第一个catch块捕获ArgumentException异常;第二个catch块捕获Exception异常。
//一个try块对应多个catch块
Console.WriteLine("输出结果是:");
}
(5)按下【Ctrl+S】键保存源代码,然后执行菜单栏中的【调试】命令9所示。
图7-9运行结果
Console.WriteLine("请输入数字b");
intb=Convert.ToInt32(Console.ReadLine());
intc=0;
try
{
//当b的值为零时抛出异常
c=a/b;
}
catch(Exceptione)
{
Console.WriteLine("发生的异常是:"+e.Message);
C#
在C#中使用try、catch、finally和throw关键字管理异常。本实验指导中介绍了使用try/catch块捕获除数异常的方法以及一个try块对应多个catch块捕获多个可能发生的异常的方法。
(1)打开Microsoft Visual Studio 2010。新建一个名为“MyApplication7_1”的项目,在该项目中新建一个“控制台应用程序”。
}
finally
{
Console.WriteLine("a/b的值是:"+c);
}
(3)在Program类中定义一个静态的方法PrintString(),当字符串为空时使用throw关键字发出出现异常的信号。
staticvoidPrintString(stringstr)
{
if(string.IsNullOrEmpty(str))