您的位置:首页 > 编程语言 > C#

C#错误和异常处理典型例子

2010-06-28 16:04 218 查看
检查用户输入的是否是一个0-5中间的数字: 多重catch块

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ExceptionDemo
{
class Program
{
static void Main(string[] args)
{
string userInput;

while (true)
{
try
{
Console.Write("Input a number between 0 and 5" + "(or just hit return to exist)>");
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 between 0 and 5." + ex.Message);
}
catch (Exception ex)
{
Console.WriteLine("An exception was thrown. Message was: {0}" + ex.Message);
}
catch
{
Console.WriteLine("Some other exception has occured");
}
finally
{
Console.WriteLine("Thank you");
}
}
}
}
}


.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

当输入的是非0-5之间的数字的时候,抛出的第一个异常,如果是一个字符串,抛出的第二个异常。第三个异常不带参数,这个catch块处理的是其他没有用C#编程的代码。

下面这个是MSDN一个try…finally的异常处理

static void CodeWithCleanup()
{
System.IO.FileStream file = null;
System.IO.FileInfo fileInfo = null;

try
{
fileInfo = new System.IO.FileInfo("C:\\file.txt");

file = fileInfo.OpenWrite();
file.WriteByte(0xF);
}
catch (System.Exception e)
{
System.Console.WriteLine(e.Message);
}
finally
{
if (file != null)
{
file.Close();
}
}
}

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: