为什么代码执行永远不会进入catch块(java)?

sim*_*mon 1 java exception-handling exception

我试图从类UserHelper中的方法importUsers抛出(自定义)ImportException.我可以在调试器中看到执行了throw子句,但调用importUsers方法的方法从不捕获异常.

这是抛出异常的方法:

public static AccessorValidator importUsers(List<String> data, WebUser actor) throws ImportException {

    //(irrelevant code removed)

    try {
        isSuccess = insertUserData(st, blocks, db, actor);
    } catch (Exception e) {
        throw new ImportException("Could not insert user on line " + rowCounter);
    }
Run Code Online (Sandbox Code Playgroud)

}

在这里,我尝试从AccessorValidator类中的execute方法捕获抛出的异常失败:

    public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    //(irrelevant code removed)
    try{
        av = UserHelper.importUsers(data, admin);
        System.out.print("test2");
    } catch (ImportException ie) {
        System.out.print("testE");
        returnMessageValue = ie.getMessage();
    } catch (Exception e) {
        System.out.print("testE2");
    }
Run Code Online (Sandbox Code Playgroud)

输出是"test2",代码执行永远不会到达任何一个catch块.我做错了什么?

Noa*_*Gal 5

尝试将您的方法更改为

try {
    isSuccess = insertUserData(st, blocks, db, actor);
    system.out.print("after insertUserData");
} catch (Exception e) {
    System.out.print("before throwing");
    throw new ImportException("Could not insert user on line " + rowCounter);
}
Run Code Online (Sandbox Code Playgroud)

这样你就可以确保你在debug中看到的是实际执行的内容(通过检查你的控制台),以及insertUserData是否实际抛出异常.