如何强制执行Catch Block?

use*_*738 19 c# exception-handling

我想知道可以try..catch强制执行进入catch并运行代码吗?

这里的示例代码:

try {
    if (AnyConditionTrue) {
      // run some code
    }
    else {
      // go catch
    }
} catch (Exception) {
    // run some code here...
}
Run Code Online (Sandbox Code Playgroud)

cad*_*ll0 28

else我建议不要在其中抛出异常,而是将代码从您catch的方法中提取出来并从其他方法中调用

try
{
    if (AnyConditionTrue)
    {
        MethodWhenTrue();
    }
    else
    {
        HandleError();
    }
}
catch(Exception ex)
{
    HandleError();
}
Run Code Online (Sandbox Code Playgroud)

  • 在我看来,我仍然更喜欢`throw new Exception`,因为可能有一些代码在`if ... else ...`下面,我不想在错误出现时执行它们 (3认同)

小智 22

   try{
      if (AnyConditionTrue){
              //run some code
               }
      else{
              throw new Exception();
          }
   }
   catch(){

      //run some code here...

   }
Run Code Online (Sandbox Code Playgroud)

但就像Yuck所说,我不会推荐这个.你应该退后一步,完成你想要完成的任务.有一种更好的方法(即使用正常的条件流,而不是异常处理).


小智 11

是的,你必须抛出异常:

  try
  {
    throw new Exception("hello");
  }
  catch (Exception)
  {

     //run some code here...
  }
Run Code Online (Sandbox Code Playgroud)


foy*_*yss 5

抛出Exception并跳转到的有效方法Catch

try
{
   throw new Exception("Exception Message");
}
catch (Exception e)
{
   // after the throw, you will land here
}
Run Code Online (Sandbox Code Playgroud)