杂谈try-catch-finally异常处理

2019-12-26 17:01:05王冬梅


using System;
using System.IO;
using System.Security.Permissions;
// Security permission request.
[assembly:FileIOPermissionAttribute(SecurityAction.RequestMinimum, All = @"c:data.txt")]
public class ProcessFile {
public static void Main() {
try {
StreamReader sr = File.OpenText("data.txt");
Console.WriteLine("The first line of this file is {0}", sr.ReadLine()); 
}
catch(Exception e) {
Console.WriteLine("An error occurred: '{0}'", e);
}
}
}

3.2. 如何:在 Catch 块中使用特定异常

发生异常时,异常沿堆栈向上传递,每个 Catch 块都有机会处理它。Catch 语句的顺序很重要。将针对特定异常的 Catch 块放在常规异常 Catch 块的前面,否则编译器可能会发出错误。确定正确 Catch 块的方法是将异常的类型与 Catch 块中指定的异常名称进行匹配。如果没有特定的 Catch 块,则由可能存在的常规 Catch 块捕捉异常。

下面的代码示例使用 try/catch 块捕获 InvalidCastException。该示例创建一个名为 Employee 的类,它带有一个属性:职员级别 (Emlevel)。PromoteEmployee 方法取得对象并增加职员级别。将 DateTime 实例传递给 PromoteEmployee 方法时,发生 InvalidCastException。


using System;
public class Employee
{
//Create employee level property.
public int Emlevel
{
get
{
return(emlevel);
}
set
{
emlevel = value;
}
}
int emlevel;
}
public class Ex13
{
public static void PromoteEmployee(Object emp)
{
//Cast object to Employee.
Employee e = (Employee) emp;
// Increment employee level.
e.Emlevel = e.Emlevel + 1;
}
public static void Main()
{
try
{
Object o = new Employee();
DateTime newyears = new DateTime(2001, 1, 1);
//Promote the new employee.
PromoteEmployee(o);
//Promote DateTime; results in InvalidCastException as newyears is not an employee instance.
PromoteEmployee(newyears);
}
catch (InvalidCastException e)
{
Console.WriteLine("Error passing data to PromoteEmployee method. " + e);
}
}
}

3.3. 如何:显式引发异常

可以使用 throw 语句显式引发异常。还可以使用 throw 语句再次引发捕获的异常。较好的编码做法是,向再次引发的异常添加信息以在调试时提供更多信息。

下面的代码示例使用 try/catch 块捕获可能的 FileNotFoundException。try 块后面是 catch 块,catch 块捕获 FileNotFoundException,如果找不到数据文件,则向控制台写入消息。下一条语句是 throw 语句,该语句引发新的 FileNotFoundException 并向该异常添加文本信息。


using System;
using System.IO;
public class ProcessFile
{
public static void Main()
{
FileStream fs = null;
try 
{
//Opens a text tile.
fs = new FileStream(@"C:tempdata.txt", FileMode.Open);
StreamReader sr = new StreamReader(fs);
string line;
//A value is read from the file and output to the console.
line = sr.ReadLine();
Console.WriteLine(line);
}
catch(FileNotFoundException e)
{
Console.WriteLine("[Data File Missing] {0}", e);
throw new FileNotFoundException(@"data.txt not in c:temp directory]",e);
}
finally
{
if (fs != null)
fs.Close();
}
}
}