gpt4 book ai didi

c# - try catch finally block 的点?

转载 作者:行者123 更新时间:2023-11-30 13:34:01 24 4
gpt4 key购买 nike

使用finally有什么区别

void ReadFile(int index)
{
// To run this code, substitute a valid path from your local machine
string path = @"c:\users\public\test.txt";
System.IO.StreamReader file = new System.IO.StreamReader(path);
char[] buffer = new char[10];
try
{
file.ReadBlock(buffer, index, buffer.Length);
}
catch (System.IO.IOException e)
{
Console.WriteLine("Error reading from {0}.
Message = {1}", path, e.Message);
}
finally
{
if (file != null)
{
file.Close();
}
}
// Do something with buffer...
}

不使用它?

void ReadFile(int index)
{
// To run this code, substitute a valid path from your local machine
string path = @"c:\users\public\test.txt";
System.IO.StreamReader file = new System.IO.StreamReader(path);
char[] buffer = new char[10];
try
{
file.ReadBlock(buffer, index, buffer.Length);
}
catch (System.IO.IOException e)
{
Console.WriteLine("Error reading from {0}.
Message = {1}", path, e.Message);
}

if (file != null)
{
file.Close();
}

// Do something with buffer...
}

最佳答案

无论是否抛出异常或抛出什么异常,前面的例子都会运行file.Close()

后者仅在未抛出异常或抛出 System.IO.IOException 时才会运行。

关于c# - try catch finally block 的点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4519584/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com