帮助处理finally块中的异常

发布于 2024-11-07 16:21:03 字数 177 浏览 7 评论 0原文

我正在尝试使用 try-catch-finally 块捕获异常。我已经在 catch 块中捕获了异常,并使用全局异常变量将其传递给finally 块。这样做,我已经处理了finally块中的异常场景。我知道这听起来很奇怪,但有必要这样做。如果有任何编码标准问题,请告诉我。另外,如果您能提出同样的建议,我将非常感激。

谢谢。

I am trying to catch an exception using a try-catch-finally block. i have caught the exception in the catch block and passed it to the finally block using a global exception variable. Doing so, i have handled the exception scenario in the finally block. I know this sounds wierd, but theres a need to do so. Please let me know if there is any coding standard issue with the same. Also if you can suggest something on the same, i will be really obliged.

Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

っ左 2024-11-14 16:21:03

catch 是捕获异常并进行任何必要的异常处理。 finally 块用于清理所有剩余打开的资源,例如文件句柄、数据库连接等。此块将大部分时间运行,因此是正确的位置进行清理,但不处理异常本身,这些应该在 catch 块中处理。

catch is to catch the exception and do any necessary exception handling. The finally block is there to clean up any left open resources, like file handles, database connections, etc. This block will most of the time run and therefore is the correct place to do cleanup, but no the handle the exceptions themselves, those should be dealt with in the catch block.

牵你手 2024-11-14 16:21:03

如果按预期使用,try-catch-finally 模式是一种非常有用且强大的模式。 建议在finally块中处理异常,并且没有多大(任何?)意义。
尝试重新组织代码以适应模式,而不是相反。

小示例:

var reader = new StreamReader(path);
try
{
   // Do your work here
   reader.ReadToEnd();
}
catch (IOException ex)
{
    // Handle specific error here
    ShowUserError(ex.Message);
}
catch (Exception ex)
{
    // Handle general error here
    LogError(ex);
}
finally
{
   // Perform clean up here
   // This code will run regardless if there was an error or not
   reader.Close();
}

此外,请查看 Try...Catch...Finally 语句

The try-catch-finally pattern is a very useful and powerful pattern, if used as intended. Handling exceptions in the finally block is not recommended and does not make much (any?) sense.
Try to reorganize your code to fit the pattern, not the other way around.

Small example:

var reader = new StreamReader(path);
try
{
   // Do your work here
   reader.ReadToEnd();
}
catch (IOException ex)
{
    // Handle specific error here
    ShowUserError(ex.Message);
}
catch (Exception ex)
{
    // Handle general error here
    LogError(ex);
}
finally
{
   // Perform clean up here
   // This code will run regardless if there was an error or not
   reader.Close();
}

Also, have a look at the MSDN documentation for Try...Catch...Finally Statements.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文