Finally 块
本课属于 Coddy C# 学习旅程的“逻辑与流程”单元。第 27 课,共 66 课。
finally 块中包含的代码总是会执行,无论是否发生异常,即使 try 或 catch 块中有 return 语句也是如此。
创建一个基本的 try-catch-finally 结构:
try
{
// 可能抛出异常的代码
int result = 10 / 2;
Console.WriteLine("Result: " + result);
}
catch (DivideByZeroException ex)
{
// 处理异常的代码
Console.WriteLine("Cannot divide by zero: " + ex.Message);
}
finally
{
// 始终会执行的代码
Console.WriteLine("This always executes");
}
finally 块适合用于清理任务,例如关闭文件或数据库连接:
System.IO.StreamReader file = null;
try
{
file = new System.IO.StreamReader("data.txt");
string content = file.ReadToEnd();
Console.WriteLine(content);
}
catch (System.IO.FileNotFoundException)
{
Console.WriteLine("File not found.");
}
finally
{
// 即使发生异常,也要确保关闭文件。
if (file != null)
{
file.Close();
}
}
挑战
简单创建一个名为 ProcessData 的方法,该方法:
- 接收一个表示文件名的字符串参数
- 尝试打开文件并读取其内容
- 将内容写入控制台
- 使用 finally 块正确清理资源
- 处理 FileNotFoundException 和 IOException
如果找不到文件,打印:"ERROR: File not found: [filename]"
如果发生其他 IO 错误,打印:"ERROR: Could not read the file: [error message]"
无论是否发生异常,都要在 finally 块中打印 "File operation completed."。
亲手试试
using System;
using System.IO;
class Program
{
public static void ProcessData(string filename)
{
// 在这里编写你的代码
}
static void Main(string[] args)
{
string filename = Console.ReadLine();
ProcessData(filename);
}
}这节课包含一个小测验。开始学习即可作答,并记录你的进度。
逻辑与流程中的所有课
自己练习: C# 在线编译器