实验环境:Windows XP,Visual Studio 2010 Ultimate
1 创建项目
文件>>新建>>项目,选中“控制台应用程序”,如下图所示:
2 添加代码如所示意。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;//添加IO操作支持
namespace testProcessException
{
class Program
{
static void Main(string[] args)
{
StreamWriter sw = null;
try
{
//尝试打开问价Test.txt,若成功则添加“Hello there”,否则发出异常
sw = new StreamWriter(new FileStream("Test.txt", FileMode.Open));
sw.WriteLine("Hello there");//打开成功则向文件中添加“Hello there”
Console.WriteLine("Message is written into file Test.txt");
}
catch (FileNotFoundException fnfe)//异常——文件不存在
{
Console.WriteLine("File" + fnfe.FileName + " not Found");
}
catch (Exception e)//异常——其他的异常
{
Console.WriteLine(e);
}
finally//这是必须执行的,不管是否有异常
{
if (sw != null)
{
sw.Close();
}
}
}
}
}
3 调试
单击菜单栏的“调试”|“启动调试”,结果如下图。
4 工程源码。点击这里下载。
参考资料
《C#实用编程百例》,清华大学出版社,何鹏飞,王征等 编著
《C#程序设计——基础教程与实验指导》——清华大学出版社,孙晓非 牛小平 冯冠 李乃文 编著
《C#程序设计与案例教程》,清华大学出版社,杨树林,胡洁萍 编著