我怎样才能强制执行到赶集? [英] How Can I Force Execution to the Catch Block?

查看:92
本文介绍了我怎样才能强制执行到赶集?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道 try..catch 是否可以强制执行进入 catch 并在其中运行代码?

I am wondering can try..catch force execution to go into the catch and run code in there?

此处为示例代码:

try {
    if (AnyConditionTrue) {
      // run some code
    }
    else {
      // go catch
    }
} catch (Exception) {
    // run some code here...
}


推荐答案

我建议不要将 catch 中的代码提取到一个 else 中,而不是将其抛出异常。方法并从其他方式调用该方法

Rather than throwing an Exception in the else, I would recommend extracting the code from your catch into a method and call that from your else

try
{
    if (AnyConditionTrue)
    {
        MethodWhenTrue();
    }
    else
    {
        HandleError();
    }
}
catch(Exception ex)
{
    HandleError();
}

这篇关于我怎样才能强制执行到赶集?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆