使用 Try/Catch 块捕捉异常
将可能引发异常的代码节放在 Try 块中,而将处理异常的代码放在 Catch 块中。Catch 块是一系列以关键字 catch 开头的语句,语句后跟异常类型和要执行的操作。
下面的代码示例使用 Try/Catch 块捕捉可能的异常。Main 方法包含带有 StreamReader 语句的 Try 块,该语句打开名为 data.txt 的数据文件并从该文件写入字符串。Try 块后面是 Catch 块,该块捕捉 Try 块产生的任何异常。
using System;
using System.IO;
using System.Security.Permissions;
// Security permission request.
[assembly:FileIOPermissionAttribute(SecurityAction.RequestMinimum, All = @"d://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);
}
}
}
using System.IO;
using System.Security.Permissions;
// Security permission request.
[assembly:FileIOPermissionAttribute(SecurityAction.RequestMinimum, All = @"d://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);
}
}
}
在 Catch 块中使用特定异常
发生异常时,异常沿堆栈向上传递,每个 Catch 块都有机会处理它。Catch 语句的顺序很重要。将针对特定异常的 Catch 块放在常规异常 Catch 块的前面,否则编译器可能会发出错误。确定正确 Catch 块的方法是将异常的类型与 Catch 块中指定的异常名称进行匹配。如果没有特定的 Catch 块,则由可能存在的常规 Catch 块捕捉异常。
下面的代码示例使用 Try/Catch 块捕捉 InvalidCastException。该示例创建一个名为 Employee 的类,它带有一个属性:职员级别 (Emlevel)。PromoteEmployee 方法取得对象并增加职员级别。将 DateTime 实例传递给 PromoteEmployee 方法时,发生 InvalidCastException。
下面的代码示例使用 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);
}
}
}
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);
}
}
}