我正在学习SSH框架,用到了struts的异常捕获机制。我自定义了一个异常类型,在异常处理类里面通过判断是否是这个类的实例来进行不同的处理。可是我能接受到的异常,全部是UndeclaredThrowableException,这个何解?一下是抛出事件的类:
`public class LoginInterceptor implements MethodBeforeAdvice {
public void before(Method method, Object[] args, Object instance)
throws Exception {
ActionMapping mapping = (ActionMapping) args[0];
ActionForm form = (ActionForm) args[1];
HttpServletRequest request = (HttpServletRequest) args[2];
HttpServletResponse response = (HttpServletResponse) args[3];
boolean needsCheck = true;
if (needsCheck && PersonUtil.getPersonInfo(request, response) == null) {
throw new TempException("您还没有登录");
}
}
}`
一下是处理异常的类
public class ForumExceptionHandler extends ExceptionHandler {
@Override
public ActionForward execute(Exception ex, ExceptionConfig ae,
ActionMapping mapping, ActionForm formInstance,
HttpServletRequest request, HttpServletResponse response)
throws ServletException {
System.out.println((ex.getClass()) + " aaaaaaa");
System.out.println((ae) + " aaaaaaa");
request.setAttribute("exception", ex);
if (ex instanceof AccountException) {
return new ActionForward("login", "/index.jsp", false);
}
return new ActionForward("exception", "/pages/exception.jsp", false);
}
}
一下是配置文件:
<global-exceptions>
<exception key="login" type="com.forum.exception.TempException"
handler="com.forum.exception.ForumExceptionHandler">
</exception>
<exception key="login" type="javax.security.auth.login.AccountException"
handler="com.forum.exception.ForumExceptionHandler">
</exception>
<exception key="login" type="java.lang.Exception"
handler="com.forum.exception.ForumExceptionHandler">
</exception>
</global-exceptions>
在您的代码中,TempException是自定义异常类型,而UndeclaredThrowableException是一种 Java 的内置异常。如果在方法中抛出的是检查型异常(即需要在方法签名中使用 throws 语句声明的异常),而方法调用者没有使用 try-catch 处理该异常,那么该异常会被封装成一个 UndeclaredThrowableException 异常抛出。
因此,可能是因为您在调用方法时没有使用 try-catch 处理 TempException 导致的。建议您在调用方法时使用 try-catch 语句处理 TempException 异常。
例如:
try {
// 调用方法
} catch (TempException e) {
// 处理 TempException 异常
}