抛出不工作

irs*_*mad 1 java try-catch throw

我有一段代码让我发疯。一般流程是,当 TRY 中的某个事件发生时,我抛出异常...根据我的理解,每当调用 时throw,它只是停止在同一个类中进一步执行,并将控制权从该类的函数所在的位置返回叫...

这是代码...

try{
    session = getHibernateSession();
    companyAccountLinkingWSBean = (CompanyAccountLinkingWSBean) wsAttribute
            .getBeanObject();

    companyToMatch = companyAccountLinkingWSBean.getCompanyCode();
    cnicToMatch = companyAccountLinkingWSBean.getCnic();

    LOG.debug("We have found the Mobile number from the WS Bean as input");

    mobile = companyAccountLinkingWSBean.getMobileNumber();
    LOG.info("Mobile is : " + mobile);
    if(mobile.isEmpty()){
        LOG.info("Coming in mobile.isEmpty()");
        companyResponceWSBean = new CompanyResponceWSBean();
        companyResponceWSBean.setpID(Constants.INPUT_MOBILE_ERROR);
        companyResponceWSBean.setMessage(Constants.INPUT_MOBILE_ERROR_MSG);
        companyResponceWSBean.setSuccess(false);
        response = new WSAttribute();
        response.setBeanObject(companyResponceWSBean);
        LOG.info("BEFORE THROWING");

        throw new PayboxFault(Constants.INPUT_MOBILE_ERROR, 
                Constants.INPUT_MOBILE_ERROR_MSG);
    }
    LOG.info("Out side IF statement!!");
} catch (Exception e) {
    LOG.info("IN Exception!!");
}
LOG.info("Out Side Exception . . . Before Returning ");
return response;  
Run Code Online (Sandbox Code Playgroud)

当空移动字段作为输入给出时,日志中的输出...

我们从 WS Bean 中找到了手机号码作为输入

手机是:

来自 mobile.isEmpty()

投掷前

例外!

外侧异常。。。回程前

实际上怎么可能呢?

Stu*_*tLC 5

你的理解不太正确。捕获异常会对其进行处理,并且在catch完成后,流程将在 后继续try/catch,除非您抛出另一个异常,或者重新抛出异常。这可能会更好地解释它:

try {
    // Happy case flow here ...
    throw new PayboxFault(...);
    // If an exception is thrown, the remainder of the `try` block is skipped
} catch (Exception e) {
    // The exception is now handled ...
    //  Unless a new exception is thrown, or the caught exception re-thrown
} finally {
   // Code here should always be called after the try OR catch block executes, 
   // Finally is called even if the catch re-throws
}
// Code after the try-catch-finally executes if the try completes successfully 
// OR if the exception is handled in the catch, but not if the catch re-throws
Run Code Online (Sandbox Code Playgroud)

  • 谢谢 Stuart,代码片段中的注释帮助我理解了 try/catch 流程。再次感谢 :) (2认同)