我有一段代码让我疯了。
一般流程是当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;
LOG中的输出当空移动字段作为输入时...
我们已经从WS Bean中找到了手机号码作为输入
手机是:
进入mobile.isEmpty()
之前
在例外!!
外线偏见。 。 。在返回之前
实际上怎么可能?
答案 0 :(得分:3)
当您捕获异常时,从catch
块之后继续执行。如果你不想要它,你需要从你的捕获内部返回(或者根本不捕获异常并让它冒泡到调用者)。
catch (Exception e)
{
LOG.info("IN Exception!!");
return null;
}
或者:
catch (Exception e)
{
...
throw e; // rethrow exception.
}
请注意,如果执行此操作,异常将继续冒泡调用堆栈,直到您将其捕获到其他位置(例如在调用方法中)。
答案 1 :(得分:3)
您的理解不太正确。捕获异常会处理它,并且在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
throw e;
} finally {
// Code here should always be called, even if the catch re-throws
}
// Code here executes only if the try completes successfully
// OR if the exception is handled in the catch
答案 2 :(得分:1)
您正在捕捉异常。因此,除非执行整个函数,否则它不会将控制权转回给调用函数。
如果你想跳过
LOG.info("Out Side Exception . . . Before Returning ");
你可以做的声明
catch (Exception e) {
LOG.info("IN Exception!!");
throw e;
}
关于
when ever the throw is called, it simply stops further execution in the same
class and return the control back from where this class's function was called...
只有在你没有抓住它时才是。如果您打算对它执行某些操作(包括记录和重新抛出),则会捕获异常。