gpt4 book ai didi

c# - 为什么 try {...} finally {...} 好;试试 {...} catch{} 不好?

转载 作者:IT王子 更新时间:2023-10-29 03:29:52 38 4
gpt4 key购买 nike

我看到有人说使用不带参数的 catch 是一种不好的形式,尤其是当 catch 什么都不做的时候:

StreamReader reader=new  StreamReader("myfile.txt");
try
{
int i = 5 / 0;
}
catch // No args, so it will catch any exception
{}
reader.Close();

然而,这被认为是好的形式:

StreamReader reader=new  StreamReader("myfile.txt");
try
{
int i = 5 / 0;
}
finally // Will execute despite any exception
{
reader.Close();
}

据我所知,将清理代码放在 finally block 中和将清理代码放在 try..catch block 之后的唯一区别是你的 try block 中是否有 return 语句(在这种情况下,清理代码in finally 会运行,但 try..catch 之后的代码不会)。

否则,finally有什么特别的?

最佳答案

最大的区别是 try...catch 会吞下异常,隐藏错误发生的事实。 try..finally 将运行您的清理代码,然后异常将继续运行,由知道如何处理它的东西处理。

关于c# - 为什么 try {...} finally {...} 好;试试 {...} catch{} 不好?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/128818/

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