How to use an UncaughtExceptionHandler in Servlets
exception, java, uncaughtexceptionhandler
Solution
That's normal. Tomcat has more than a hundred threads, and the uncaught exception handlers are associated to a given thread (it's coming from the time of `ThreadGroups`).
What you can do is to wrap the contents of the `doPost()` in a `try-catch` block.
The other way is to define error handling in the `web.xml` - you can also create a servlet for handling errors in other servlets :-) See an example here.
Problem
I implemented an UncaughtExceptionHandler on StartUp of tomcat: ``` Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler() { @Override public void uncaughtException(Thread t, Throwable e) { LOGGER.error("Uncaught Exception"); } }); ``` When I produce an Exception in a Servlet it is not caught by my Handler: ``` protected void doPost(HttpServletRequest req, HttpServletResponse resp) { int i = 1/0; ``` The console says: Feb 13, 2014 8:23:58 AM org.apache.catalina.core.StandardWrapperValve invoke Schwerwiegend: Servlet.service() for servlet [ConnectGatewaysServlet] in context with path [/infraview] threw exception java.lang.ArithmeticException: / by zero at net.test.gateway.ConnectGatewaysServlet.doPost(ConnectGatewaysServlet.java:73) at javax.servlet.http.HttpServlet.service(HttpServlet.java:647) at javax.servlet.http.HttpServlet.service(HttpServlet.java:728) How do I implement an UncaughtExceptionHandler for Servlets?