C# - 在 catch 子句中使用 return

标签 c# .net try-catch

我在这里看到了类似的问题,但还有一些地方我不明白。据我所知,当你使用 try-catch block 时,如果抛出异常,catch block 将在之后立即执行,并且 catch 子句之后没有代码代码块将被执行。所以如果我做对了,如果我们有:

try
{
    // do something
    // throw an exception for some reason
}
catch (Exceptiox ex)
{
    // do something when there is and exception thrown
}
// some code that will never be runned if and exception was thrown above

我不是 100% 确定 catch 会停止超出其范围的进一步执行,但这是我的问题之一,如果我错了请纠正我。

那么,如果您根本不需要返回任何值,那么在 catch block 中使用 return 有什么意义呢?我在我正在处理的继承代码的某些方法中看到了这一点。例如:

public void DeleteImage(AppConfig imageInfo, string imageName)
{
    string imgPath = imageInfo.ConfigValue.ToString();
    try
    {
        File.Delete(imgPath + "\\" + imageName);
    }
    catch (Exception ex)
    {
        logger.Error(ex.ToString());
        return;
    }
}

这里除了记录错误外不需要做任何事情。为什么要使用 return。这是一个错误吗?如果您不显式return,方法不会结束吗?如果 catch 子句之后有更多代码,如果 return 不存在并且 catch 仅用于记录错误?

最佳答案

I'm not 100% sure that the catch stops further execution outside it's scope but this is one of my questions so correct me if I'm wrong.

不,那是不正确的。执行将在 catch block 之后正常继续,除非 block 内的某些代码改变了流程(例如 throwreturn)。

因此,如果您不想继续执行,return 是必需的。即使在 catch block 之后当前没有代码,恕我直言,可以更明确地说明“处理此类异常涉及在此之后不执行任何代码” .

也就是说,您应该警惕 catch (Exception ex) —— 捕获所有类型的异常应该始终受到质疑,而且几乎总是不正确的做法(尽管在这种情况下它用于日志记录,这是“允许的规则异常(exception)”)。

关于C# - 在 catch 子句中使用 return,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15335381/

相关文章:

c# - 如何从 xmlReader 的当前节点创建 xmlElement?

c# - 列 abc 不属于表?

c# - 哪个更快 : filtering a DataSet in-memory or returning a result set from SQL Server?

c# - Azure 辅助角色错误处理

c# - ThreadPool 或 Task 是否适合用于服务器?

java - 两次捕获相同的异常

c# - 使用 c# 将 Messagebox.show() 保持在其他应用程序之上

C# Application.Run without Form

powershell - 为什么错误会通过 Powershell 中的 TRY/CATCH 循环

c++ - 在 C++0x 中模拟 finally block