要了解try...catch...finally块是如何工作的,最简单的方式是用示例来说明。示例SimpleException.它多次要求用户输入数字,然后显示这个数字。为了便于解释这个示例,假如必须在0~5之间。否则程序就不能对该数字进行正确的处理。所以,如果用户输入超出该范围的数字,就会抛出异常。
Using System;
namespace Wrox.ProCSharp.AdvancedCSharp
{
public class MainEntryPoint
{
while (true)
{
try
{
string userInput;
Console.WriteLine("input a number between 0 and 5" + "(or just hit return to exit)>0");
userInput = Console.ReadLine();
if (userInput == "")
{
break;
}
int index = Convert.ToInt32(userInput);
if (index < 0 || index > 5)
{
throw new IndexOutOfRangeException("you typed in" + userInput);
}
Console.WriteLine("your number was" + index);
}
catch (IndexOutOfRangeException ex)
{
Console.WriteLine("Exception:" + "Number should be between 0 and 5.{0}", ex.Message);
}
catch(Exception ex)
{
Console.WriteLine("An exception was thrown.Message was:{0}",ex.Message);
}
finally
{
Console.WriteLine("Thank you");
}
}
}
}
Using System;
namespace Wrox.ProCSharp.AdvancedCSharp
{
public class MainEntryPoint
{
while (true)
{
try
{
string userInput;
Console.WriteLine("input a number between 0 and 5" + "(or just hit return to exit)>0");
userInput = Console.ReadLine();
if (userInput == "")
{
break;
}
int index = Convert.ToInt32(userInput);
if (index < 0 || index > 5)
{
throw new IndexOutOfRangeException("you typed in" + userInput);
}
Console.WriteLine("your number was" + index);
}
catch (IndexOutOfRangeException ex)
{
Console.WriteLine("Exception:" + "Number should be between 0 and 5.{0}", ex.Message);
}
catch(Exception ex)
{
Console.WriteLine("An exception was thrown.Message was:{0}",ex.Message);
}
finally
{
Console.WriteLine("Thank you");
}
}
}
}