The only way to handle this in the general case is to use web.xml , as shown below:
<error-page> <exception-type>java.lang.Throwable</exception-type> <location>/ErrorHandler</location> </error-page>
Servlet throws ServletException and IOException , but if you want to handle runtime exceptions and all other exceptions in one exception handler, you can specify the type of exception as Throwable . You can use multiple error page entries that will handle different types of exceptions and have different handlers.
Example:
@WebServlet("/ErrorHandler") public class ErrorHandler extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processError(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processError(request, response); } private void processError(HttpServletRequest request, HttpServletResponse response) throws IOException {
source share