Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/288.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/sharepoint/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 帮助处理最后一个块中的异常handlin_C#_.net_Exception Handling_Try Catch Finally - Fatal编程技术网

C# 帮助处理最后一个块中的异常handlin

C# 帮助处理最后一个块中的异常handlin,c#,.net,exception-handling,try-catch-finally,C#,.net,Exception Handling,Try Catch Finally,我试图使用try-catch-finally块捕获异常。我在catch块中捕获了异常,并使用全局异常变量将其传递给finally块。这样,我在finally块中处理了异常场景。我知道这听起来很奇怪,但有必要这样做。请让我知道,如果有任何编码标准的问题与相同的。如果你能提出同样的建议,我将不胜感激 谢谢。catch用于捕获异常并执行任何必要的异常处理。finally块用于清理任何遗留打开的资源,如文件句柄、数据库连接等。该块大部分时间都会运行,因此是进行清理的正确位置,但不会自行处理异常,这些应该

我试图使用try-catch-finally块捕获异常。我在catch块中捕获了异常,并使用全局异常变量将其传递给finally块。这样,我在finally块中处理了异常场景。我知道这听起来很奇怪,但有必要这样做。请让我知道,如果有任何编码标准的问题与相同的。如果你能提出同样的建议,我将不胜感激


谢谢。

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

如果按预期使用,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();
}

另外,请查看MSDN文档。

需要什么?你本可以摆脱
catch
blog并拥有
finally
block。你不会将异常传递给finally block。你能澄清一下你试图解决的问题吗?肯定有更好的方法来解决它!并非总是: