Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/301.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#-finally子句内的异常处理_C#_Exception Handling - Fatal编程技术网

C#-finally子句内的异常处理

C#-finally子句内的异常处理,c#,exception-handling,C#,Exception Handling,这个标题有点误导人,但我觉得这个问题很直截了当。我有try catch finallyblock。仅当从try块引发异常时,我才希望执行finally块中的代码。该守则目前的结构如下: try { //Do some stuff } catch (Exception ex) { //Handle the exception } finally { //execute the code only if exception was thrown. } 现在我能想到的唯一解决办法是设置一

这个标题有点误导人,但我觉得这个问题很直截了当。我有
try catch finally
block。仅当从
try
块引发异常时,我才希望执行
finally
块中的代码。该守则目前的结构如下:

try
{
  //Do some stuff
}
catch (Exception ex)
{
  //Handle the exception
}
finally
{
  //execute the code only if exception was thrown.
}
现在我能想到的唯一解决办法是设置一个标志,如:

try
{
  bool IsExceptionThrown = false;
  //Do some stuff
}
catch (Exception ex)
{
  IsExceptionThrown = true;
  //Handle the exception   
}
finally
{
if (IsExceptionThrown == true)
  {
  //execute the code only if exception was thrown.
  }
}

并不是说我看到了一些不好的地方,而是想知道是否有另一种(更好的)方法来检查是否有抛出的异常?

最后不要为此使用
。它适用于应该始终执行的代码

在何时执行方面,两者之间的区别到底是什么

//Handle the exception


我什么也看不见

最后不要使用
。它适用于应该始终执行的代码

在何时执行方面,两者之间的区别到底是什么

//Handle the exception


我什么也看不见

比如:

try
{
    // Do some stuff
}
catch (Exception ex)
{
    // Handle the exception
    // Execute the code only if exception was thrown.
}
finally
{
    // This code will always be executed
}

这就是
Catch
block的用途

比如:

try
{
    // Do some stuff
}
catch (Exception ex)
{
    // Handle the exception
    // Execute the code only if exception was thrown.
}
finally
{
    // This code will always be executed
}

这就是
Catch
block的用途

无论是否发现异常,Try/Catch语句的最后部分始终被激发。我建议您不要在这种情况下使用它

try
{
  // Perform Task
}
catch (Exception x)
{
  //Handle the exception error.

}
Finally
{
  // Will Always Execute.
}

无论是否发现异常,Try/Catch语句的最后一部分始终被激发。我建议您不要在这种情况下使用它

try
{
  // Perform Task
}
catch (Exception x)
{
  //Handle the exception error.

}
Finally
{
  // Will Always Execute.
}

毕竟,您最终不需要

try
{
  //Do some stuff
}
catch (Exception ex)
{
  //Handle the exception
  //execute the code only if exception was thrown.
}

毕竟,您最终不需要

try
{
  //Do some stuff
}
catch (Exception ex)
{
  //Handle the exception
  //execute the code only if exception was thrown.
}

为什么不把代码放在catch()部分呢?您要查找的是存在于CLR中的
fault
,但从未在C#中实现过。@Laurent-我想实际的用法是,如果有多个
catch
子句,那么如果出现任何异常,应该执行的一些常见代码将是一个更重要的例子。@Damien#u不信者同意。如果只能用作开关/案例…为什么不将代码放在catch()部分?您要查找的是CLR中存在的
故障
,但从未在C#中实现过。@Laurent-我想实际的用法是,如果有多个
catch
子句,那么如果出现任何异常,应该执行的一些常见代码将是一个更重要的例子。@Damien#u不信者同意。如果能作为开关/外壳使用就好了。。。