Why does code execution never enter catch block (java)?
I am trying to throw a (custom) ImportException from the importUsers method in the UserHelper class. I can see in the debugger that the throw clause is being executed, but the method from which the importUsers method is called never gets caught.
Here is the method in which the exception is thrown:
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);
}
}
Here's where I'm trying unsuccessfully to catch the thrown exception from the execute method in the AccessorValidator class:
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");
}
The result is "test2" and the code execution never hits any of the catch blocks. What am I doing wrong?
source to share
try changing your method to
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);
}
so you can verify that what you see when debugging is what is actually being executed (by checking your console) and whether insertUserData is throwing an exception or not.
source to share
Check the following:
- make sure your breakpoints are in sync with your source
-
insertUserData()
does not throw an exception at all, check if it should throw an exception at all or not. It looks like you are expecting something that will never happen. - Make sure it is
ImportException
indeed the same object in both cases when you refer to it
source to share
If the output is "test2" then of course no exception was thrown.
Just guess ...
Sometimes your IDE may not be in sync with the source code that is actually being executed, especially if your code is part of an external library ... If you change the library code and do not update the actual one classpath
, or if this change occurs while debugging, the lines of code may change and you can see that an exception will be thrown even though it doesn't really happen.
source to share
try to catch Throwable, the root of the exception and error, with:
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");
} catch (Throwable t) {
// Here you'll catch *anything* else
System.out.print("testTE");
}
source to share