Are there situations where it is appropriate to use a try-finally block without a catch block?

推荐答案

You would use it to ensure some actions occur after the try content or on an exception, but when you don't wish to consume that exception.

Just to be clear, this doesn't hide exceptions. The finally block is run before the exception is propagated up the call stack.

You would also inadvertently use it when you use the using keyword, because this compiles into a try-finally (not an exact conversion, but for argument's sake it is close enough).

try
{
    TrySomeCodeThatMightException();
}
finally
{
    CleanupEvenOnFailure();
}

Code running in finally is not guaranteed to run, however the case where it isn't guaranteed is fairly edge - I can't even remember it. All I remember is, if you are in that case, chances are very good that not running the finally isn't your biggest problem :-) so basically don't sweat it.

Update from Tobias: finally will not run if the process is killed.

Update from Paddy: Conditions when finally does not execute in a .net try..finally block

The most prevalent example you may see is disposing of a database connection or external resource even if the code fails:

using (var conn = new SqlConnection("")) // Ignore the fact we likely use ORM ;-)
{
    // Do stuff.
}

Compiles into something like:

SqlConnection conn;

try
{
    conn = new SqlConnection("");
    // Do stuff.
}
finally
{
    if (conn != null)
        conn.Dispose();
}

.net相关问答推荐

安装特定主要版本的DotNet SDK最新版本

";Make Async ValueTask/ValueTask方法分期分配发生了什么?

将多行参数传递给Power Shell中的DotNet Pack命令

为什么Regex.Escape支持数字符号和空格?

使用 SSH.NET 查找具有特定文件名的最新 SFTP 文件

如何在 Windows 窗体上显示 ClickOnce 版本号

每当属性值发生变化时引发事件?

关于在 .NET 中干净地终止线程的问题

在 C# 中输入按键

如何从 appsettings.json 中获取价值

支持 HTTPS 的 Httplistener

C# 的 Actors 有什么好的实现吗?

什么版本的 .NET 附带什么版本的 Windows?

如何从 XDocument 获取 Xml 作为字符串?

ToLowerInvariant() 有什么问题?

是否可以在 XP 上运行 .NET 4.5 应用程序?

使用 lambda 表达式代替 IComparer 参数

为什么 .NET 中没有 Tree 类?

C# 应用程序中的资源和嵌入式资源有什么区别?

如何为 Dapper 查询动态创建参数