我已经开始主要在Struts和Servlets上开发Java EE Web应用程序。大多数代码在Servlet或Struts Action类中都有一个try catch块。
是否必须为每个servlet或操作都设置try catch块?我用这种代码模板看到的唯一好处是stacktrace是将日志记录到应用程序指定的日志框架,例如log4j。
如果运行时异常 float ,它将被打印在服务器(Tomcat/Glassfish/Weblogic)日志中。
public class HelloWorldAction extends Action{
public ActionForward execute(ActionMapping mapping,ActionForm form,
HttpServletRequest request,HttpServletResponse response)
throws Exception {
try {
// do all the processing here
} catch (Exception e) {
// log all exceptions
}
}
}
public class HelloWorldExample extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
try {
// do all the processing here
} catch (Exception e) {
// log all exceptions
}
}
}
最佳答案
Exception
几乎从来不是您真正想要做的。希望很明显,始终拥有try/catch块不是强制性的-它取决于基础代码在做什么,以及您希望如何处理它可能引发的任何异常。Exception
消除了使用Struts' declarative exception handling的能力。我建议不要使用过滤器来处理Struts 1中的异常,因为它已经内置了机制。如果在框架级别存在异常,则无论如何都会显示它们,并且它们通常表示开发而不是运行时问题。
我赞同安德里亚的观点:除非您有很好的理由,否则学习Struts 1不会有用。可以考虑将Struts 2或Spring MVC用于“传统”框架开发,或者考虑使用Play,Grails,JRuby on Rails等,以获得更现代的方法。